我试图检查用户给出的单词是否已经存在于文本文件中,或者它的子字符串是否已存在.这是我的代码:
String ans = null; Scanner scanner = null; do { System.out.print("Please enter a new word: "); String Nword = scan.next(); System.out.print("And its appropriate Hint: "); String Nhint = scan.next(); Word word = new Word(Nword , Nhint); File file = new File("C:\\Users\\Charbel\\Desktop\\Dictionary.txt"); file.createNewFile(); scanner = new Scanner(file); if (scanner != null) { String line; while (scanner.hasNext()) { line = scanner.next(); for(int i = 0 ; iEclipse说
else
条件之后的语句是"死代码",我不知道为什么.
scanner = new Scanner(file);
scanner
被初始化,永远不会null
,所以else
永远不会达到这个陈述.
看到构造函数:
抛出:
FileNotFoundException
- 如果找不到来源
因此,如果file
不存在,scanner
将不存在null
,您将有例外.