[英]Reading integers from text file
我試圖從文本文件中讀取整數,但失敗了。 (它甚至無法讀取第一個整數)
public void readFromFile(String filename) {
File file = new File(filename);
try {
Scanner scanner = new Scanner(file);
if (scanner.hasNextInt()) {
int x = scanner.nextInt();
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("File to load game was not found");
}
}
我得到的錯誤是:NoSuchElementException。 該文件如下所示:
N,X1,Y1,X2,Y2,X3,Y3
在此示例中,n等於3。
我在主要方法中將此方法稱為a:
readFromFile("file.txt");
我不確定在將整數與字符串分開后是否只顯示整數。 如果是這樣,我建議您使用BufferedInputStream。
try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)))){
String input = br.readLine();
int count = 0;
for(int i = 0; i < input.length()- 1; i++){
if(isNumeric(input.charAt(i))){
// replace the Sysout with your own logic
System.out.println(input.charAt(i));
}
}
} catch (IOException ex){
ex.printStackTrace();
}
其中isNumeric可以定義如下:
private static boolean isNumeric(char val) {
return (val >= 48 && val <=57);
}
Scanner
使用空格作為默認定界符。 您可以使用useDelimiter
進行更改,請參見此處: https : useDelimiter
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.