I’m having trouble with an assessment working out why my .txt file isn’t being read in the substringProblem. Currently it gives the output dictionary.txt – not found instead of reading the file. My code in main states the file was opened but I’m unsure what I need to change in the substringProblem to process it there. Can anyone point me in the right direction?
package wordgames;
//@author Kris
import java.util.Scanner;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class WordGames {
public static final String DICTIONARY = "dictionary.txt";
public static void main(String[] args) throws FileNotFoundException {
File file = new File(DICTIONARY);
if (file.isFile()) {
System.out.println("Succesfully opened the file: " + DICTIONARY);
} else {
System.out.println("Unable to open the file: " + DICTIONARY);
System.exit(0);
}
getSelection();
}
public static int getSelection() throws FileNotFoundException {
Scanner input = new Scanner(System.in);
String menu = """
Welcome to the Word Games program menu.
Select from one of the following options.
1. Substring problem.
2. Points Problem
3. Exit
""";
System.out.println(menu);
boolean wrongInput;
do {
System.out.printf("Enter your selection: ");
int selection = input.nextInt();
wrongInput = false;
switch (selection) {
case 1:
substringProblem();
break;
case 2:
pointsProblem();
break;
case 3:
System.out.println("Goodbye!");
break;
default:
System.out.println("Please choose between 1 and 3");
wrongInput = true;
break;
}
} while (wrongInput);
return 0;
}
public static void substringProblem() {
Scanner input = new Scanner(System.in);
Scanner File = new Scanner(DICTIONARY);
String choice = "";
String word = "";
String answer = "";
System.out.println("Substring problem.");
System.out.printf("Enter a substring:");
choice = input.nextLine();
while (File.hasNextLine()) {
int line = 1;
line++;
word = File.nextLine();
if (word.startsWith(choice)) {
answer = word + " - Prefix found";
System.out.println(answer);
} else {
System.out.println(word + " - not found");
}
}
}
public static void pointsProblem() {
System.out.println("Points Problem.");
}
}
>Solution :
Passing a String to the Scanner constructor doesn’t make a scanner which reads the file with that name:
/**
* Constructs a new {@code Scanner} that produces values scanned
* from the specified string.
*
* @param source A string to scan
*/
public Scanner(String source) {
this(new StringReader(source), WHITESPACE_PATTERN);
}
You need to pass a Path:
Scanner file = new Scanner(Path.of(DICTIONARY));