Ok so I have a text file like so
dears fears
heart heart
sail ruin
etc
I'm trying to run the scanner through each line so I can
create a WordLadder object which requires the 2 strings in each line.
try {
Scanner sc = new Scanner(new File("input.txt"));
while (sc.hasNext()) {
String s = sc.next();
String s2 = sc.next();
WordLadder wl = new WordLadder(s, s2);
System.out.print(wl.toString());
}
}
catch (FileNotFoundException ex)
System.out.print("File not found");
}
For some reason, when I run the debugger, as far as I can tell, it runs through once then it waits for user input. It creates a word ladder with dears and fears and prints the solution for that word ladder. Then second loop it waits for user input instead of doing it again.
I'm thoroughly confused because when I do something like this
try {
Scanner sc = new Scanner(new File("input.txt"));
while (sc.hasNext()) {
String s = sc.next();
System.out.println(s);
}
}
catch (FileNotFoundException ex)
{
System.out.print("File not found");
}
It prints all the words. But any variation I tried of trying to put those words in a wordladder object it waits for user input. Any ideas?
I just tried your code and I have no issues unless I have a file with an odd number of Strings. In that case, I get the following error:
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at Main.main(Main.java:19)
This is expected since you are reading 2 Strings for each sc.hasNext().
So it seems to me that the issue might be the content of your input.txt file.
Related
I'm trying to read multiple lines from a text file before reaching a certain string, "***", which I would then like to print out. How do I do this?
Code:
public void loadRandomClass(String filename) {
try {
Scanner scan = new Scanner(new File(filename));
while((scan.hasNextLine()) && !(scan.nextLine().equals("***"))) {
}
scan.close();
} catch (FileNotFoundException e) {
System.out.println("Something went wrong");
e.printStackTrace();
}
}
I have tried some stuff, but it keeps skipping every 2nd line, starting from the 1st and it doesn't stop before "***".
The problem is that scan.nextLine() reads the line and deletes it from the buffer i suppose. Try this:
while(scan.hasNextLine()) {
String next = scan.nextLine();
if(next.contains("***") break;
System.out.println(next);
}
I've been programming Monopoly on java and I've been running into a NumberFormatException when I pull the rent values from a .txt file.
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
Here's the code:
try{
//Searching for .txt file
fileName = "N://java/Monopoly/src/rent.txt";
//creating FileReader and BuffReader objects
FileReader input = new FileReader(fileName);
BufferedReader bufRead = new BufferedReader(input);
//reading first line
String line = bufRead.readLine();
while(line!=""){
//not sure why, but program doesn't run well without if statement
if(line!=""){
//creating array of in variable
splitArr = line.split(",");
//creating rent object
rent r = new rent(Integer.parseInt(splitArr[0]),Integer.parseInt(splitArr[1]),Integer.parseInt(splitArr[2]),Integer.parseInt(splitArr[3]),Integer.parseInt(splitArr[4]),Integer.parseInt(splitArr[5]));
//storing rent object to a public static Arraylist holding all rents for the game
rents.add(r);
//debugging code that has been commented out
//System.out.println(r.toString());
}
//debugging code that has been commented out
/*for(String s : splitArr){
System.out.print(s+", ");
}*/
//reading next line
line = bufRead.readLine();
}
//closing IO stream
bufRead.close();
//preventing out of bounds exception error
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("Usage: java ReadFile filename: rent\n");
//preventing IOException error
}catch (IOException e){
e.printStackTrace();
//I can't quite remember I have this in there. I know it didn't work right without it at some point
}catch(NullPointerException e){
}
When I uncomment the enhanced for loop at line 16, I get some values followed by the error and then all of the rest of the values as if there was no problem. I have noticed that when I delete and re-enter the values where the error begins, the error moves to other places. I've checked the arguments in the rent class (it requires 6 int's) and have checked the .txt file where all the values are good.
How do I fix this or should I not worry about it and add another catch statement to ignore the error?
You're comparing strings with !=. You should use !line.equals(""). – Saviour Self
I am trying to output a file scanner object from my method. This is a school assignment and I am specifically instructed to NOT throw any exceptions, but use try/catch instead. The assignment requires that the command line prompt the user for a file to scan. If the file does not exist, we are supposed to tell the user, then prompt them for a file again. If the file does exist, then the method returns a scanner object that scans the file.
My code works, but it is not clean. It involves 2 methods. This is my code so far:
public static Scanner getInputScanner (Scanner console) {
File inputFile = null;
Scanner input = null;
try {
inputFile = getFile(inputFile, console);
input = new Scanner (inputFile);
return input;
} catch (FileNotFoundException e) {
try {
return input = new Scanner (getFile (inputFile, console));
} catch (FileNotFoundException f) {
System.out.println("An error has occured.");
return input;
}
}
}
public static File getFile (File inputFile, Scanner console) {
System.out.println("Enter input file: ");
inputFile = new File (console.nextLine());
while (!inputFile.exists()) {
System.out.println("File does not exist.");
System.out.print("Enter input file: ");
inputFile = new File (console.nextLine());
}
return inputFile;
}
The problem with the code is that the output looks like this:
Enter input file:
File does not exist.
Enter input file:
It then is waiting for the user's input. I don't want the output to have the 2 lines of code before the last line though.
Can anybody explain why my code is outputting these 2 lines?
Also, is there a simpler solution to getting an input file without throwing the FileNotFoundException?
Thanks!
If I understand correctly,
your program outputs these lines when you run it,
no matter what,
without you getting a chance to actually enter a filename.
Enter input file:
File does not exist.
And then the programs asks you again:
Enter input file:
And you don't want the first two lines above, right?
This can happen for example if the Scanner console you received has an unread newline in it.
You haven't posted that part of the code,
so it's hard to tell, but this is a common gotcha with Scanner.
Before calling getInputScanner,
make sure the Scanner console is ready to use,
with no unread garbage still buffered in it.
As for the second part of your question,
yes this can be written simpler and better, for example:
public static Scanner getInputScanner(Scanner console) {
try {
File inputFile = getExistingFile(console);
return new Scanner(inputFile);
} catch (FileNotFoundException e) {
throw new AssertionError("The file is expected to exist (was supposed to be verified earlier)");
}
}
public static File getExistingFile(Scanner console) {
while (true) {
System.out.println("Enter input file: ");
File inputFile = new File(console.nextLine());
if (inputFile.exists()) {
return inputFile;
}
System.out.println("File does not exist.");
}
}
It execute below line as soon the getFile() being called.
System.out.print("Enter input file: ");
Since no file exist, the below lines keeps on executing :
while (!inputFile.exists()) {
System.out.println ("File does not exist.");
System.out.print("Enter input file: ");
You can use throws() instead of try/catch, then caller will take care of exception.
Had to consume whatever junk was being carried over from the scanner by inserting a Scanner.nextLine() before getting user input. Final code looks like this:
public static Scanner getInputScanner(Scanner console) {
try {
File inputFile = getExistingFile(console);
return new Scanner(inputFile);
} catch (FileNotFoundException e) {
throw new AssertionError("The file is expected to exist (was supposed to be verified earlier)");
}
}
public static File getExistingFile(Scanner console) {
while (true) {
console.nextLine();
System.out.println("Enter input file: ");
File inputFile = new File(console.nextLine());
if (inputFile.exists()) {
return inputFile;
}
System.out.println("File does not exist.");
}
}
I am not sure while am receiving a no such element exception. It seems to be an issue with the scanner not reading my file correctly, but I am not sure where I am going wrong.
I am reading a file, then using the scanner to go line by line. But I get unusual behavior, such as missing lines or filenotfound exceptions when I try to do it.
public static void readMylifeLikeABook(String fileName,int maxItems) {
// Read file line by line with different elements on each line
int bookCount=0;
int movieCount = 0;
Book [] bookItem =new Book[maxItems];
Movie [] movieItem =new Movie[maxItems];
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
Scanner line;
while (scanner.hasNext() && ((bookCount+movieCount)<maxItems)) {
line = new Scanner(scanner.nextLine()); // scan next line
if (line.next().contains("Movie")){
movieItem[movieCount]= new Movie();
movieItem[movieCount].setMediaType("Movie");
movieItem[movieCount].setTitle(scanner.nextLine());
movieItem[movieCount].setRef(scanner.nextLine());
movieItem[movieCount].setPrice(Double.valueOf(scanner.nextLine()));
movieItem[movieCount].setDirector(scanner.nextLine());
movieItem[movieCount].setActor(scanner.nextLine());
System.out.println(movieItem[movieCount].getTitle());
movieCount++;
line.close(); // close line
}
else if (scanner.next().contains("Book")){
bookItem[bookCount]= new Book();
bookItem[bookCount].setMediaType("Book");
bookItem[bookCount].setTitle(scanner.nextLine());
bookItem[bookCount].setRef(scanner.nextLine());
bookItem[bookCount].setPrice(Double.valueOf(scanner.nextLine()));
bookItem[bookCount].setAuthor(scanner.nextLine());
System.out.println(bookItem[bookCount].getTitle());
bookCount++;
line.close(); // close line
}
}
scanner.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
//System.out.println(count);
for (int i=0;i<(bookCount+movieCount);i++) {
System.out.println(bookItem[i] +"\n\n "+ movieItem[i]);
}
}
Hmm, is it possible if you can provide the file being read? This can very well be a problem with that File as if the Scanner object does not a following line to be read, it will throw an exception. Make sure the file has the needed amount of lines.
You call line.next() immediately after constructing line. Do you need to do this? If so, perhaps you need to call hasNext() first to ensure there's a token there.
(I'm pretty sure line.next() throws a NoSuchElementException if there's no token.)
Also, check your code against the file format. Are there blank lines in your file?
I have this problem with a method using the Scanner class. I am reading my text file with Scanner and then parse the int into an array.
public static void readItems()
{
try
{
File file = new File(System.getProperty("user.home") + "./SsGame/item.dat");
Scanner scanner = new Scanner(file);
int line = 0;
while (scanner.hasNextLine())
{
String text = scanner.nextLine();
text = text.replaceAll("\\W", "");
System.out.println(text.trim());
PlayerInstance.playerItems[line] = Integer.parseInt(text);
line++;
}
scanner.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (NumberFormatException e2)
{
e2.printStackTrace();
}
}
Heres the item.txt file:
1
1
2
3
4
I run the code and I get the following output:
1
I have tried using scanner.hasNextInt() and scaner.nextInt(); for this but then it won't print anything at all.
If I remove the parseInt part then the file will finish reading and all the numbers will be printed. Any ideas?
This the exception thrown:
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at game.player.ReadPlayer.readItems(ReadPlayer.java:56)
at game.player.ReadPlayer.read(ReadPlayer.java:11)
at game.Frame.<init>(Frame.java:32)
at game.Frame.main(Frame.java:54)
I'm guessing Integer.ParseInt() is throwing an NumberFormatException because your line still contains the \n.
If you call Integer.ParseInt(text.trim()) instead, it may fix it.
If you did your Exception handling properly, we would have a better idea.
This is because, you have a NumberFormatException, while parsing integer.
Add in catch section something like this
System.out.println(e.getCause());
And see, that you have an exception, that's why this code prints only first digit.
You need to be careful when you use the Scanner.
If you are reading more data, with Scaner like input.nextInt(); then it will read only one int. The carriage return isn't consumed by nextInt. One solution is that add input.nextLine(); so that it moves to the next line.
Other Solution is, which I prefer is to use BufferedReader;
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String tempStr = bufferRead.readLine();
// Do some operation on tempStr
Hope this helps.