[英]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.