简体   繁体   English

从文件中读取两位数并避免使用空格/字符串(Java)

[英]Reading double digits from a file and avoiding whitespace/strings (Java)

I am trying to read from a file and add my numbers to an array. 我试图从文件中读取并将我的数字添加到数组中。 The file can contain white spaces and strings but I only need the digits. 该文件可以包含空格和字符串,但我只需要数字。

0
4
xxx
52

23

Here is my code so far: 到目前为止,这是我的代码:

Scanner scanner = new Scanner(new File("file.txt"));
int i=0;
while(scanner.hasNextInt() && count < 15) {   //only need first 15 digits
    arr[i++] = scanner.nextInt();
    count+= 1;
}

The code currently works but it stops once it reaches a string or any whitespace. 代码当前有效,但一旦到达字符串或任何空格就会停止。

Your while will quit when it hits the first non-integer. 当你遇到第一个非整数时,你的while会退出。 You need to change the condition: 你需要改变条件:

// Loop until eof or 15 numbers
while(scanner.hasNext() && count < 15) {   //only need first 15 digits
    // Have a number?
    if (scanner.hasNextInt()) {
        arr[i++] = scanner.nextInt();
        count+= 1;
    }
    // Not a number, consume.
    else {
        scanner.nextLine();
    }
}

Try with this: 试试这个:

while (scanner.hasNext() && count < 15) { // use Scanner::hasNext 
    if (scanner.hasNextInt()) {           // if is number then add it to the array
        arr[i++] = scanner.nextInt();
        count++;
    } else {                             
        scanner.next();                   // else ignore the value
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM