簡體   English   中英

從文件中讀取兩位數並避免使用空格/字符串(Java)

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

我試圖從文件中讀取並將我的數字添加到數組中。 該文件可以包含空格和字符串,但我只需要數字。

0
4
xxx
52

23

到目前為止,這是我的代碼:

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;
}

代碼當前有效,但一旦到達字符串或任何空格就會停止。

當你遇到第一個非整數時,你的while會退出。 你需要改變條件:

// 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();
    }
}

試試這個:

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