在读取一个简单文件时,我试图只从中获取数字。
Hi 80
Bye 90
Cool 100
使用制表符空格的扫描仪分隔符将帮助我忽略数字之前的空格,但是当我尝试获取数字本身时,它会在之后获取类似 80Bye 的内容。有什么办法可以解决这个问题吗?
编辑:
Scanner scan = new Scanner(new File("score.txt"));
scan.useDelimiter(" ");
while( scan.hasNext() ){
name=scan.next();
System.out.println(name);// Prints Hi
num=scan.next();
scan.nextLine();
scan.delimiter();
System.out.println(num); //Prints 80
// Bye
holdAvg+=Integer.parseInt(num); // Error occurs
count++;
}
当我尝试输入数字 80 时,Bye 紧随其后。我也尝试过使用“\n”分隔符,但它也不起作用。当我使用“\n”时,它说当我尝试解析它时,“100”变成 int 时出现错误。
最佳答案
无需设置显式分隔符,默认(空白)就可以了:
Scanner scan = new Scanner(new File("score.txt"));
while( scan.hasNext() )
{
System.out.println("Word: " + scan.next());
System.out.println("Number: " + scan.nextInt());
}
try catch block 对于确保程序在收到意外输入时不会崩溃非常有用。
Integer.parseInt(..)
抛出 NumberFormatException
和scan.nextInt()
抛出 InputMismatchException
.
请参阅扫描仪上的 javadoc:https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
关于java - 只读取文件输入中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35817923/