我在这里有一个.txt文件“C:\ failass.txt”。它包含以下信息:
AA051245445454552117989
LT647044001231465456
LT517044077788877777
LT227044077788877777
CC051245445454552117989
我找到了一个代码,用于扫描用户输入是否与文件中包含的信息匹配:
package ibanas;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class ReadFromFile {
public static void main(String[] args) throws IOException {
Scanner myScanner = new Scanner(System.in);
System.out.println("What number would you like to check for?");
String number = myScanner.nextLine();
if(isFound(number)){
System.out.println("The number "+number+ " is there");
}else{
System.out.println("The number "+number+ " doesn't exist");
}
}
public static boolean isFound(String number) {
Scanner sc = new Scanner(ReadFromFile.class.getResourceAsStream("C:\failass.txt"));
String word="";
while (sc.hasNextLine()) {
word = sc.next();
if (word.equals(number.trim())) {
return true;
}
}
return false;
}
}
但是当我输入(例如)此行AA051245445454552117989时,它会给我以下错误:
What number would you like to check for?
AA051245445454552117989
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Unknown Source)
at java.io.InputStreamReader.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at ibanas.ReadFromFile.isFound(ReadFromFile.java:24)
at ibanas.ReadFromFile.main(ReadFromFile.java:15)
感谢您的任何建议:)
答案 0 :(得分:0)
扫描程序的arg,即ReadFromFile.class.getResourceAsStream("C:\failass.txt")
返回null。可能是因为你需要用另一个"C:\\failass.txt"