I am trying to find a way to deal with the NoSuchElementException error thrown by a Scanner object when reading the last item in my text file with NO SPARE LINE. This means that my cursor will end after the last character of the last line in the file
EXAMPLE:
score.txt
[Test;Word|]
[ & ] denotes the start and end of the text file
The | is where the cursor ends.
I know that if my cursor ends a line below it, my Scanner will not throw the NoSuchElementException because there is a nextLine.
What i want to achieve is to ensure that the NoSuchElementException is not thrown when the spare line is missing. Is there a way to prevent the error from occurring besides making sure that the spare line is there?
My Driver class simply calls the method importWordList() from class WordGame.
The code for WordGame is very long so I will only upload the method importWordList() from the class.
public boolean importWordList(String fileName) throws FileNotFoundException
{
//Set default return value
boolean returnVal = false;
//Set File to read from
File wordListDest = new File(fileName);
if (wordListDest.canRead() == true)
{
lineS = new Scanner(wordListDest);
//Read each line from file till there is no line
while (lineS.hasNextLine())
{
//Set delimeter scanner to use delimeter for line from line scanner
String line = lineS.nextLine();
delimeterS = new Scanner(line);
delimeterS.useDelimiter(";");
//Read each delimeted string in line till there is no string
while (delimeterS.hasNextLine())
{
//Store Variables for quiz object
wordAndHint = delimeterS.nextLine();
answer = delimeterS.nextLine(); //ERROR
//Create Object Quiz and add to wordList
Quiz addWord = new Quiz(wordAndHint, answer);
wordList.add(addWord);
}
delimeterS.close();
}
lineS.close();
returnVal = true;
System.out.println("Word List has been Imported Successfully!");
}
else
{
System.out.println("The file path you selected either does not exist or is not accessible!");
}
return returnVal;
}
The Error that occurs is as Follows:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1516)
at mysterywordgame.WordGame.importWordList(WordGame.java:74)
at mysterywordgame.Main.main(Main.java:60)
The error (at mysterywordgame.WordGame.importWordList(WordGame.java:74)) refers to line with the comment ERROR.
I have searched around for ways to prevent the error from occurring, however, all answers were "Make sure there is a spare line at the end of the text file"
Some help will be much appreciated.
As you already consumed the next line with wordAndHint = delimeterS.nextLine(); you have to check for next line again:
if(delimeterS.hasNextLine()){
answer = delimeterS.nextLine();
}else{
answer = "";
}
Related
So I am making a program that renders pictures from .ppm files. I have got another version working but have now moved on to the other part which is reading multiple images from the same document and to basically use this to animate it with a small delay inbetween switching pictures, and then the following error has come up and am completely stumped by it:
java.io.ioexception is never thrown in body of corresponding try statement
Any help would be much appreciated.
public void renderAnimatedImage(){
String image = UI.askString("Filename: ");
int keepingCount =0; //Variables
int numCount = 1;
try{
Scanner fileScan = new Scanner(image); // making scanners
Scanner scan = new Scanner(image);
File myFile = new File(image); //making files
File myFile2 = new File(image);
int num = 0;
while(scan.hasNextLine()){
String Line = scan.nextLine();
Scanner keywordSc = new Scanner (Line);
while(keywordSc.hasNext()) {
String Keyword = keywordSc.next();
if (Keyword.equals("P3")) {
num++;
}
else { break; }
}
}
while (keepingCount< numCount) {
this.renderImageHelper(scan); // calling upon an earlier method which works.
keepingCount++;
}
}
catch(IOException e) {UI.printf("File failure %s \n", e); }
}
It means the code you're writing inside your try/catch is never throwing an IOException, which makes the clause unnecessary. You can just remove it and keep your code without it.
I bet that you think there could be an IOException because of this line:
Scanner fileScan = new Scanner(image); // making scanners
But that line is not doing what you think it does. Since image is a String this will use the Scanner(String) constructor. But that constructor treats its argument as a string to be scanned, not the name of a file to be scanned.
Hence new Scanner(image) is not doing any I/O and is not declared as throwing an IOException.
And the rest of the code in the block won't throw IOException either. The Scanner next / hasNext methods that you are using will throw a different exception if there is an I/O error while reading. (Check the javadocs.)
Also, you seem to be misunderstanding what File is / does.
File myFile = new File(image); //making files
The comment is incorrect. That does not make a file.
Actually, it makes a File object which is an in-memory representation of a filename / pathname. Creating a File object doesn't cause a file to be created in the file system. (Again, check the javadocs.)
My prof posted this to practice exception handling and reading and writing to textfiles:
Write a method called removeFirstWord
removeFirstWord returns an int and takes two strings as arguments.
The first argument is the name of the input file and the second the name of
the output file.
It reads the input file as a text file one line at the time. It removed the first word from each line and write the resulting line to the output file. sometext.txt below is an example input file with output.txt the expected output file.
If the input file does not exist, the method should throw FileNotFoundException. If the input file is empty, the method should throw EmptyFileException. The method should not throw any other exceptions.
If an exception other than FileNotFoundException is thrown, the method should return -1. Otherwise, the method returns 0."
This was his code:
public static int removeFirstWord(String inputFilename, String outputFilename) throws FileNotFoundException, EmptyFileException {
int lineCounter = 0;
try {
BufferedReader input = new BufferedReader(new FileReader(inputFilename));
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFilename)));
String line = input.readLine();
while (line!=null){
lineCounter++;
String[] words = line.split(" ");
for (int index = 1; index < words.length; index++) {
String word = words[index];
writer.print(word + " ");
}
writer.println();
line = input.readLine();
}
writer.flush();
writer.close();
input.close();
} catch (IOException ioe) {
return -1;
}
if (lineCounter == 0) {
throw new EmptyFileException();
}
return 0;
}
I do not understand why she used an array. Can't you just read the first word and stop at a space and write that word to the output file and jump to the next line?
Also I do not understand the difference between doing a throws FileNotFoundException, EmptyFileException vs just doing a catch?
First thing First- Actually, you are little bit confused with her requirement. Actually, she wants to remove only the all first words of all line from the given text file and remain words will be there in the output file.
So, for this she choose to convert a complete line into an String array. the other possible way was to do substring the given line but that will be costly in time complexity.
Second why she used throws instead a catch block because as per the business requirement the was no use to catch the both exception, she wants to catch it later or wants to show it to the end user.
I think this will help you out.
I wanted to delete a line from a textfile after asking the user what he/she wants to delete but I don't know what to do next in my code.
The textfile looks like this:
1::name::mobileNum::homeNum::fax::birthday::email::website::address // line the user wants to delete
2::name::mobileNum::homeNum::fax::birthday::email::website::address
3::name::mobileNum::homeNum::fax::birthday::email::website::address
Here's my code:
public static void readFromFile(String ans, String file) throws Exception {
BufferedReader fileIn = new BufferedReader(new FileReader(file));
GetUserInput console = new GetUserInput();
String checkLine = fileIn.readLine();
while(checkLine!=null) {
String [] splitDetails = checkLine.split("::");
Contact details = new Contact(splitDetails[0], splitDetails[1], splitDetails[2], splitDetails[3], splitDetails[4], splitDetails[5], splitDetails[6], splitDetails[7], splitDetails[8]);
checkLine = fileIn.readLine();
if(ans.equals(splitDetails[0])) {
// not sure what the code will look like here.
// in this part, it should delete the line the user wants to delete in the textfile
}
}
}
So the output of the textfile should be like this:
2::name::mobileNum::homeNum::fax::birthday::email::website::address
3::name::mobileNum::homeNum::fax::birthday::email::website::address
Also, I want the line number 2 and 3 to be adjusted to 1 and 2:
1::name::mobileNum::homeNum::fax::birthday::email::website::address
2::name::mobileNum::homeNum::fax::birthday::email::website::address
How would I do this?
Here's a working code, assuming you are using Java >= 7:
public static void removeLine(String ans, String file) throws IOException {
boolean foundLine = false;
try (BufferedReader br = Files.newBufferedReader(Paths.get(file));
BufferedWriter bw = Files.newBufferedWriter(Paths.get(file + ".tmp"))) {
String line;
while ((line = br.readLine()) != null) {
String[] tokens = line.split("::", 2);
if (tokens[0].equals(ans)) {
foundLine = true;
} else {
if (foundLine) {
bw.write((Integer.parseInt(tokens[0]) - 1) + "::" + tokens[1]);
} else {
bw.write(line);
}
bw.newLine();
}
}
}
Files.move(Paths.get(file + ".tmp"), Paths.get(file), StandardCopyOption.REPLACE_EXISTING);
}
It is not possible to delete a line from a file. What you need to do is read the existing file, write the contents you want to keep to a temporary file and then rename the temporary file to overwrite the input file.
Here, the temporary file is created in the same directory as the input file, with the extension .tmp added (note that you can also use Files.createTempFile for this).
For each line that is read, we check if this is the line the user wants to delete.
If it is, we update a boolean variable telling us that we just hit the line to be deleted and we do not copy this line to the temporary file.
If it is not, we have a choice:
Either we did not yet hit the line to be deleted. Then we simply copy what we read to the temporary file
Or we did and we need to decrement the first number and copy the rest of the line to the temporary file.
The current line is splitted with the help of String.split(regex, limit) (it splits the line only two times, thereby creating an array of 2 Strings: first part is the number, second part is the rest of the line).
Finally, the temporary file overwrites the input file with Files.move (we need to use the REPLACE_EXISTING option).
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java - Find a line in a file and remove
I am trying to remove a complete line from a text file, and have managed to remove the line if there is only one single unbroken line of text without spaces. If i have a space delimiter between strings it fails to remove anything.
Code as follows:
import java.io.*;
import java.util.Scanner;
public class removebooks {
// construct temporary file
public static void main(String[]args)throws IOException {
String title;
Scanner titlerem= new Scanner (System.in);
System.out.println("Enter Title to remove from file");
title = titlerem.next ();
// construct temporary file
File inputFile = new File("books.txt");
File tempFile = new File(inputFile + "temp.txt");
BufferedReader br = new BufferedReader (new FileReader("books.txt"));
PrintWriter Pwr = new PrintWriter(new FileWriter (tempFile));
String line = null;
//read from original, write to temporary and trim space, while title not found
while((line = br.readLine()) !=null) {
if(line.trim().equals(title)){
continue; }
else{
Pwr.println(line);
Pwr.flush();
}
}
// close readers and writers
br.close();
Pwr.close();
titlerem.close();
// delete book file before renaming temp
inputFile.delete();
// rename temp file back to books.txt
if(tempFile.renameTo(inputFile)){
System.out.println("Update succesful");
}else{
System.out.println("Update failed");
}
}
}
the text file is called books.txt and contents simply should look like:
bookone author1 subject1
booktwo author2 subject2
bookthree author3 subject3
bookfour author4 subject4
thank you any help would be appreciated
Why don't you use
if(line.trim().startsWith(title))
instead of
if(line.trim().equals(title))
because equals() is only true if both strings are equal, and startsWith() is true if line.trim() starts with title ;)
As you are reading the file line by line. You can make use of following
if(line.contains(title)){
// do something
}
In this case you will not be limited by title only.
String API
br.readLine() sets the value of variable line to "bookone author1 subject1".
Scanner.next() delimits by whitespace. You need to consolidate all your calls to Scanner.next() to a single String before checking against the lines in the file, if that is your intent.
In your case, if you typed "bookone author1 subject1", value of variable title would be "bookone" after your call to Scanner.next().
I am writing a program that reads the input from a file and then prints it to the screen. When I run it without taking the input from the file, it works perfectly fine. However, every time I try to run it from the file it gives me an "Exception in thread "main" java.util.NoSuchElementException: No line found at" error that occurs every place the input is suppose to be read. I have no idea what is going on.
This program is suppose to take the input from the user, create a Photo object, and then print the information to the screen. Everything runs fine when I am entering the information manually but when I try to use java PhotoTest < test.dat to get the input for a file it gives this error message:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1516)
at PhotoTest.readPhoto(PhotoTest.java:31)
at PhotoTest.main(PhotoTest.java:74)
My code that has input:
private static Photo readPhoto(Scanner scanner) throws ParseException
{
Date dateTaken;
Scanner scan = new Scanner(System.in);
String subject = scan.nextLine();
subject = subject.trim();
String location = scan.nextLine();
location = location.trim();
String date = scan.nextLine();
date = date.trim();
if (date.equals("")){ //if the date is empty it is set to null
dateTaken = null;
}
else { //if a date is entered, it is then parsed
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
dateTaken = df.parse(date);
}
String file = scan.nextLine();
file = file.trim();
File photoFile = new File(file);
//creates a Photo object from the information entered
Photo Photo = new Photo(subject, location, dateTaken, photoFile);
return Photo;
}
public static void main(String[] args) throws ParseException
{
boolean endprogram = false;
Scanner scan = new Scanner(System.in);
//creates a loop so that the user may enter as many photos as they wish
while (!endprogram)
{
System.out.println("Would you like to enter a photo (y/n)?");
//if the input is anything other than y, the program ends
if(!scan.next().equalsIgnoreCase("y"))
{
endprogram = true;
}
else
{
System.out.println(readPhoto(scan));
}
}
}
Everything runs fine when I am entering the information manually but when I try to use java PhotoTest < test.dat to get the input for[sic?] a file [...]
Does test.dat contain the "y" confirmations too? When you pipe in a file for stdin, the content of that file must be in legal format as if it was typed in manually.
Also, you are creating another Scanner instance for stdin even though one is already passed to readPhoto. Are you sure you need to do this?
In your file you need a carriage return in the last line. That would be the equivalent to what you are typing manually. Note that when you are typing, in the last line you press enter.