Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to create a java program that recieves a .txt file and plays the game, then prints it all into a new file (named by the user). I've reached the point where all the words have been chosen but am getting a NoSuchElementException message after that. I have a pretty basic knowledge of java and absolutely no clue how to proceed. Anyone have suggestions?
import java.io.*;
import java.util.*;
public class MadLibs {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
intro();
//in order to create the output file first prompts user to decide
//whether they want to create a mad-lib, view their mad-lib or quit
//if 'c' is selected then while loop is exited
String action = "c";
String fileName = "fileName";
while (action.equals("c")) {
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
action = console.nextLine();
action = action.toLowerCase();
File file = new File(fileName);
System.out.print("Input file name: ");
while (!file.exists()) {
fileName = console.nextLine();
file = new File(fileName);
if (!file.exists()) {
System.out.print("File not found. Try again: ");
}
}
//asks for a file to read from for the mad-lib game
//and creates file (named by user) to input the information
System.out.print("Output file name: ");
String outputName = console.nextLine();
System.out.println();
File outputFile = new File(outputName);
PrintStream output = new PrintStream(outputFile);
Scanner tokens = new Scanner(file);
while (tokens.hasNext()) {
String token = tokens.next();
//calls the returned placeHolder
String placeHolder = placeHolder(console, tokens, token);
String newWord = madLib(console, token, placeHolder);
//copies each token and pastes into new output file
}
}
while (action.equals("v")) {
System.out.print("Input file name: ");
fileName = console.nextLine();
File outputFile = new File(fileName);
if (!outputFile.exists()) {
System.out.print("File not found. Try again: ");
fileName = console.nextLine();
} else {
PrintStream output = new PrintStream(outputFile);
output = System.out;
}
}
while (action.equals("q")) {
}
}
public static String madLib(Scanner console, String token, String
placeHolder) throws FileNotFoundException{
String word = placeHolder.replace("<", "").replace(">", ": ").replace("-",
" ");
String startsWith = String.valueOf(word.charAt(0));
if (startsWith.equalsIgnoreCase("a") || startsWith.equalsIgnoreCase("e")
||
startsWith.equalsIgnoreCase("i") || startsWith.equalsIgnoreCase("o")
||
startsWith.equalsIgnoreCase("u")) {
String article = "an ";
System.out.print("Please type " + article + word);
String newWord = console.next();
return newWord;
} else {
String article = "a ";
System.out.print("Please type " + article + word);
String newWord = console.next();
return newWord;
}
}
public static String placeHolder(Scanner console, Scanner tokens, String
token) throws FileNotFoundException {
while(!(token.startsWith("<") && token.endsWith(">"))) {
//not a placeholder!
//continue reading file
token = tokens.next();
}
//outside of this while loop = found a placeholder!!
String placeHolder = token;
//returns placeholder to main
return placeHolder;
}
//method prints out the introduction to the game
public static void intro() {
System.out.println("Welcome to the game of Mad Libs");
System.out.println("I will ask you to provide various words");
System.out.println("and phrases to fill in a story.");
System.out.println("The result will be written to an output file.");
System.out.println();
}
}
Also am currently using a file called simple.txt with the text:
I wannabe a <job> when I grow up.
Just like my dad.
Life is <adjective> like that!
This is the full error message:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at MadLibs.placeHolder(MadLibs.java:96)
at MadLibs.main(MadLibs.java:46)
I ran your code and got a NoSuchElementException instead of a NoSuchFileException. To circumvent this exception you need to check if there are any more tokens while in the method placeHolder. Otherwise, after entering every placeholder you would still search for the next placeholder token although there is no next().
Change your code to:
while(tokens.hasNext() && !(token.startsWith("<") && token.endsWith(">"))) {
//not a placeholder!
//continue reading file
System.out.println(token);
token = tokens.next();
}
Related
I am working on student registration system. I have a text file with studentname, studentnumber and the student's grade stored in every line such as:
name1,1234,7
name2,2345,8
name3,3456,3
name4,4567,10
name5,5678,6
How can I search a name and then return the whole sentence? It does not get any matches when looking for the name.
my current code look like this:
public static void retrieveUserInfo()
{
System.out.println("Please enter username"); //Enter the username you want to look for
String inputUsername = userInput.nextLine();
final Scanner scanner = new Scanner("file.txt");
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if(lineFromFile.contains(inputUsername)) {
// a match!
System.out.println("I found " +inputUsername+ " in file " ); // this should return the whole line, so the name, student number and grade
break;
}
else System.out.println("Nothing here");
}
The problem is with Scanner(String) constructor as it:
public Scanner(java.lang.String source)
Constructs a new Scanner that produces values scanned from the
specified string.
Parameters: source - A string to scan
it does not know anything about files, just about strings. So, the only line that this Scanner instance can give you (via nextLine() call) is file.txt.
Simple test would be:
Scanner scanner = new Scanner("any test string");
assertEquals("any test string", scanner.nextLine());
You should use other constructor of Scanner class such as:
Scanner(InputStream)
Scanner(File)
Scanner(Path)
You already have the variable that holds the whole line. Just print it like this:
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if(lineFromFile.contains(inputUsername)) {
// a match!
System.out.println("I found " +lineFromFile+ " in file " );
break;
}
else System.out.println("Nothing here");
}
I've been stuck with this error for 3 hours, it is because in my CSE course we just learned to put in "throws FileNotFoundException" in methods however in my code:
public static void main(String[] args) throws FileNotFoundException {
Scanner user = new Scanner(System.in);
intro();
prompt(user);
}
public static void prompt(Scanner user) throws FileNotFoundException {
boolean game = true;
while(game != false) {
System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
String answer = user.next();
answer = answer.toUpperCase();
if(answer.equals("C")) {
create(user);
} else if(response == "V") {
view(user);
} else if(answer.equals("Q")) {
game = false;
}
}
}
public static void create(Scanner user) throws FileNotFoundException {
System.out.print("Input file name: ");
String fileName = user.nextLine();
Scanner file = new Scanner(new File(fileName));
File f = new File(fileName);
if(!f.exists()) {
System.out.print("File not found. Try again: ");
fileName = user.nextLine();
f = new File(fileName);
}
System.out.print("Output file name: ");
PrintStream ot = new PrintStream(new File(user.nextLine()));
filing(user, fileName, ot);
}
When ran through, and inputting in C: this is what happens.
Welcome to the game of Mad Libs.
I will ask you to provide various words
and phrases to fill in a story
The result will be written to an output file
(C)reate mad-lib, (V)iew mad-lib, (Q)uit? c
Input file name: Exception in thread "main" java.io.FileNotFoundException: (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.util.Scanner.<init>(Scanner.java:656)
at MadLibs.create(MadLibs.java:47)
at MadLibs.prompt(MadLibs.java:35)
at MadLibs.main(MadLibs.java:16)
Really confused for this in my CSE class, and I feel like they did not explain the process enough even after asking questions. Can anyone explain this? Thanks.
First of all you need to change the "fix" the following line:
String answer = user.next();
to read:
String answer = user.nextLine();
This means you will capture the newline, meaning it won't be buffered until the next Scanner call (preventing you from reading the filepath prompt).
Then some fixing here too. No need to create a new Scanner, you already have one which you can use:
System.out.print("Input file name: ");
String fileName = user.nextLine();
File f = new File(fileName);
if(!f.exists()) {
Since you are using user.next() to get the user input at first the scanner is reading the only next character but not the newline character.
So later on in your code when you do:
System.out.print("Input file name: ");
String fileName = user.nextLine();
The user.nextLine() call is just reading in the newline character left behind by the user.next() call.
One way you can fix this is by reading nextLine but ignoring the input like so:
user.nextLine();
System.out.print("Input file name: ");
String fileName = user.nextLine();
Now when prompted for the file name it will work correctly.
I am having issues with my synonym map. I want to be able to search a text file for a keyword or a related word in the textfile then outputting the found sentence. so my program searches for the answers to questions based on the keyword or sunonym. the way my program works is by searching a text file for a keyword in the question and then outputting the answer to the question which is the next line after then question in the text file. When i search for the main keyword in a question the program works. But when i try to ask a question with the related word the program does not recognize the input. So for example if i enter "how is the major?" the answer to that question is on the next line which is "the major is difficult" but if i enter "how is the focus" the program does not recognize the related word focus Can someone help me find the issue which lies in searching for a related word also. Here is my text file
what is the textbook name?
the textbook name is Java
how is the major?
the major is difficult
how much did the shoes cost?
the shoes cost two dollars
how is the major when cramer took it?
when cramer took it, it was okay
how is the major when jar took it?
jar said it was fine
what is the color of my bag?
the color of my bag is blue
and here is my code
public static class DicEntry {
String key;
String[] syns;
Pattern pattern;
public DicEntry(String key, String... syns) {
this.key = key;
this.syns = syns;
pattern = Pattern.compile(".*(?:"
+ Stream.concat(Stream.of(key), Stream.of(syns))
.map(x -> "\\b" + Pattern.quote(x) + "\\b")
.collect(Collectors.joining("|")) + ").*");
}
}
public static void parseFile(String s) throws IOException {
List<DicEntry> synonymMap = populateSynonymMap(); // populate the map
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
Scanner forget = new Scanner(System.in);
int flag_found = 0;
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
for (DicEntry entry : synonymMap) { // iterate over each word of the
// sentence.
if (entry.pattern.matcher(s).matches()) {
if (lineFromFile.contains(entry.key)) {
//String bat = entry.key;
if(lineFromFile.contains(s)) {
String temp = scanner.nextLine();
System.out.println(temp);
}
}
}
}
}
}
private static List<DicEntry> populateSynonymMap() {
List<DicEntry> responses = new ArrayList<>();
responses.add(new DicEntry("bag", "purse", "black"));
responses.add(new DicEntry("shoe", "heels", "gas"));
responses.add(new DicEntry("major", "discipline", "focus", "study"));
return responses;
}
public static void getinput() throws IOException {
Scanner scanner = new Scanner(System.in);
String input = null;
/* End Initialization */
System.out.println("Welcome ");
System.out.println("What would you like to know?");
System.out.print("> ");
input = scanner.nextLine().toLowerCase();
parseFile(input);
}
public static void main(String args[]) throws ParseException, IOException {
/* Initialization */
getinput();
}
}
It would seem that after you pass
if (lineFromFile.contains(entry.key))
in your parseFile(String s) method, you would want to know if your user entered input contains any of the entry.syns and replace the synonym with the key
// This is case sensitive
boolean synonymFound = false;
for (String synonym : entry.syns) {
if (s.contains(synonym)) {
s = s.replace(synonym, entry.key)
break;
}
}
Since you want to stop searching once you find a match (exact or synonym match), you'll want to have a return statement to kick out of the method or use a flag to kick out of the while (scanner.hasNextLine())
if (lineFromFile.contains(s)) {
String temp = scanner.nextLine();
System.out.println(temp);
flag_found = 1;
System.out
.println(" Would you like to update this information ? ");
String yellow = forget.nextLine();
if (yellow.equals("yes")) {
// String black = scanner.nextLine();
removedata(temp);
} else if (yellow.equals("no")) {
System.out.println("Have a good day");
// break;
}
// Add return statment to end the search
return;
}
Results:
This is a workout program which asks the user for his name and creates a file where all his data is stored. Inside that file, there are 3 literals: fullName, age and experience.
The feature which is not working is printing out all the information inside the file, when the user enters his username.
So, if I had an account called Bob, and I entered Bob in the console, I should get my fullName, my Age and my experience. (which had already been stored in the file before).
This is my method for reading data from the file and printing it out. I ran it several times with the debugger but it only reads the title of the file and not the information inside it. The result is "Could not find file". How do I fix this? Thanks.
public void getInfo(String nameIn) {
Scanner keyboard = new Scanner(System.in);
Scanner x;
out.println("\nWhat's your account's name?");
nameIn = keyboard.nextLine();
//It reads the title of the file, not the data inside it.
try {
x = new Scanner(nameIn);
if (x.hasNext()) {
String a = x.next();
String b = x.next();
String c = x.next();
out.println("Account data for user: " + nameIn);
out.printf("Name: %s \tAge: %s \tExperience: %s", a, b, c);
}
} catch (Exception e) {
out.println("Could not find file.");
}
Here's the rest of the code in that class.
public class createMember {
public String name;
private String fullName;
private String age;
private String experience;
private Formatter x;
public createMember(String name) {
this.name = name;
}
public void setMembership() {
try {
x = new Formatter(name);
out.println("File with name \"" + name + "\" has been created!");
} catch (Exception e) {
out.println("Could not create username.");
}
}
public void setInfo() {
Scanner keyboard = new Scanner(System.in);
out.println("Enter your Full Name");
fullName = keyboard.nextLine();
out.println("Enter your Age");
age = keyboard.nextLine();
out.println("Enter your lifting experience");
experience = keyboard.nextLine();
x.format("Name: %s \tAge: %s \tExperience: %s", fullName, age, experience);
}
public void getInfo(String nameIn) {
Scanner keyboard = new Scanner(System.in);
Scanner x;
System.out.println("\nWhat's your account's name?");
nameIn = keyboard.nextLine();
//It reads the title of the file, not the data inside it.
try {
File file = new File("nameOfYourFile.txt");
x = new Scanner(file);
while (x.hasNextLine())) {
String line = x.nextLine();
if (line.contains(nameIn)){ // or you can use startsWith()
// depending how your text is formatted
String[] tokens = line.split(" ");
String a = tokens[0].trim();
String b = tokens[1].trim();
String c = tokens[2].trim();
System.out.println("Account data for user: " + nameIn);
System.out.printf("Name: %s \tAge: %s \tExperience: %s", a, b, c);
}
}
} catch (FileNotFoundException e) {
System.out.println("Could not find file.");
}
You have to pass an InputStream to your scanner, not the name of the file.
final String pathToFile = "/my/dir/" + nameIn;
x = new Scanner(new FileInputStream(new File(pathToFile)));
Even though I must say I have never seen this approach to read a file line by line. I usually do this using a BufferedLineReader.
Checking hasNext() once and invoking next() thrice is not a good design. Any of the next() calls after the first might fail if no more tokens are available.
So, one possibility is that you're running out of tokens after the first x.next() call.
Another possibility is that the given pathname nameIn does not correspond to any file on the file system.
Also, you should be catching exception using more specific types instead of Exception. If you had done that, you would have known which of the new Scanner(file) or x.next() threw exception.
Please bear with me here as I'm new to the site.
below is a program that I've written for my programming in Java class, and while most of it has gone well so far, I can't seem to get rid of a specific bug.
When the program reaches the third if block (choice == 3) it doesn't let the user enter any data, and if the line
"outputStream = openOutputTextFile(newerFileName);"
is present in the if block then a FileNotFoundException occurs. After tinkering around with my code for a while I've found that the error is being thrown because the program cannot find the inputStream anymore. Although I've checked and have found that the program can still find, read, and write to the file that is throwing the error.
I'm thinking that since the error only occurs when I put the outputStream in, and is being thrown by the inputStream, then it probably has something to do with file streams. I just don't know what exactly
Does anyone have any ideas on how I could solve this issue?
public class FileProgram {
public static PrintWriter openOutputTextFile(String fileName)
throws FileNotFoundException {
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
public static Scanner readFile(String fileName)
throws FileNotFoundException {
Scanner inputStream = new Scanner(new File(fileName));
return inputStream;
}
public static void main(String args[]) throws FileNotFoundException {
ArrayList<String>fileReader = new ArrayList<String>(10);
PrintWriter outputStream = null;
Scanner inputStream = null;
Scanner keyboard = new Scanner(System.in);
try {
System.out.println("Enter the name of the text file you want to copy.");
String oldFileName = keyboard.nextLine();
inputStream = readFile(oldFileName);
while(inputStream.hasNextLine()) {
String currentLine = inputStream.nextLine();
fileReader.add(currentLine);
}
System.out.println("All data has been collected. Enter the name for the new text file");
String newFileName = keyboard.nextLine();
outputStream = openOutputTextFile(newFileName);
File userFile = new File(newFileName);
if(userFile.exists())
{
System.out.println("The name you entered matches a file that already exists.");
System.out.println("Here are your options to fix this issue.");
System.out.println("Option 1: Shut down the program.");
System.out.println("Option 2: Overwrite the old file with the new empty one.");
System.out.println("Option 3: Enter a different name for the new file.");
System.out.println("Enter the number for the option that you want.");
int choice = keyboard.nextInt();
if(choice == 1) {
System.exit(0);
} else if(choice == 2) {
outputStream = new PrintWriter(newFileName);
} **else if(choice == 3) {
System.out.println("Enter a different name.");
String newerFileName = keyboard.nextLine();
outputStream = openOutputTextFile(newerFileName);
}**
}
for(int i = 0; i < fileReader.size(); i++) {
String currentLine = fileReader.get(i);
outputStream.println(currentLine);
//System.out.println(currentLine);
}
System.out.println("The old file has been copied line-by-line to the new file.");
}
catch(FileNotFoundException e) {
System.out.println("File not found");
System.out.println("Shutting program down.");
System.exit(0);
}
finally {
outputStream.close();
inputStream.close();
}
}
}
You are having trouble getting a line of input from your Scanner object after calling .nextInt(). In response to the numeric choice, the user enters an integer followed by a newline.
This line reads the integer from the input buffer:
int choice = keyboard.nextInt();
However, there's still a newline in the input buffer right after the number. Thus when you call .nextLine():
String oldFileName = keyboard.nextLine();
You get an empty line. You cannot create a file with an empty string for a file name, so a FileNotFoundException is thrown (this is per spec, see the other answer).
One solution is to consistently use .nextLine(), getting a line at a time from the input buffer. When you need an integer, simply parse the string manually:
int choice = Integer.parseInt( keyboard.nextLine() );
By the way, in debugging this sort of issue it's very useful to get into the habit of adding some printout statements to see what's going on:
public static PrintWriter openOutputTextFile(String fileName)
throws FileNotFoundException {
System.out.println( "Trying to create file: '" + fileName + "'" );
PrintWriter toFile = new PrintWriter(fileName);
return toFile;
}
There are more advanced debugging techniques, but this one is extremely simple, and using it is a lot more effective than using nothing at all.