[英]Scanner won't work on mac. I think it is unable to accept the int value from a method
在课堂上,我被教导如何使用扫描仪读取文件。 我们编写的这段代码在Windows(eclipse)上有效,但在mac(coderunner)上无效。 图像包含此项目中使用的文本文件。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
String fileName = "/Users/User1/Desktop/example.rtf";
File textFile = new File(fileName);
Scanner in = new Scanner(textFile);
int value = in.nextInt();
System.out.println("Read value: " + value);
in.nextLine();
int count = 2;
while(in.hasNextLine()){
String line = in.nextLine();
System.out.println(count + ": " + line);
count++;
}
in.close();
}
}
// Output Below
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Main.main(Main.java:14)
Process finished with exit code 1
至于您的问题,尽管该文件是文本文件,但不是程序假定的纯文本文件。 它使用的是RTF格式 ,这是一种可以处理格式化文本的特殊格式。
如果使用纯文本编辑器(或在终端中使用less
的语言)打开它,则会看到实际的内容。
要解决您的问题,您应该将其保存为未经格式化的格式 ,例如example.txt
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.