I am trying to check if the word given by the user already exists in the text file or a substring of it already exists. Here's my code:
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 ; i<line.length(); i++)
if ((line.equals(Nword)) || (Nword.equals(line.substring(i))))
{
System.out.println("The word already exists.");
break;
}
}
}
else
{
FileWriter writer = new FileWriter(file , true);
writer.write(word.toString());
writer.write(System.lineSeparator());
writer.flush();
writer.close();
System.out.println("Your word has successfuly added.");
System.out.print("\nWould you like to add another word ?\nPress 0 to continue.");
ans = scan.next();
}
} while(ans.equals("0"));
Eclipse said that the statements after the else
condition are "Dead Code" and I don't know why.
scanner = new Scanner(file);
scanner
is initialized, can never be null
, so the else
statement will never be reached.
See the constructor:
Throws:
FileNotFoundException
- if source is not found
So if the file
doesn't exists, scanner
won't be null
, you'll have an exception.