NoSuchElementException when using do while loop - java

I'm working on my College project and I keep getting this exception when I try to make all my code loop. When not in a loop it works perfectly fine, it includes creating text files and appending text files (if thats any help). My assumption is that my scanner is causing these problems, but I don't know what the problem is or how to fix it.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:855)
at java.util.Scanner.next(Scanner.java:1478)
at java.util.Scanner.nextInt(Scanner.java:2108)
at java.util.Scanner.nextInt(Scanner.java:2067)
at PDispenser_V1.main(PDispenser_V1.java:51)
I can't post my code because plagiarism software checks stackoverflow and my full project will be plagiarised if I do. I know that's a huge downfall but if you could tell me what to look for in general and how to fix it (provided I gave you enough to go on) that would be great! Also the only line number the complier gave me that exists is 51 and it has this code on it.
selection = input.nextInt();
This line is followed by a switch statement with a bunch of methods in each case. If theres anything I can answer without showing any code please ask. Any help is appreciated.
EDIT: I should also say, it complies fine but when I go to select one of the options again thats when it throws the exception.
EDIT2: I should also mention that the selection is taking a line from the user not a file.

You are probably using nextInt without checking if there is one available to read on the stream, as the javadoc for nextInt says:
Throws:
NoSuchElementException - if input is exhausted
Try using hasNextInt() to check if there is an int before attempting to read one from the stream.

Exception is throwing because, there is no next token for the input to return.
To avoid such exceptions it is always best practice to first check the existence of next token using input.hasNextInt() . If it returns true then extract the next token using input.nextInt(). Example.
if (input.hasNextInt())
{
int i = input.nextInt();
}
EDIT
This Error can be produced in following way:
public class Scanned
{
public static void main(String st[])
{
Scanner input = null;
try
{
InputStream in = System.in;
input = new Scanner (in);
while (true)
{
System.out.println(input.nextInt());
in.close();
}
}
catch (Exception ex)
{
System.out.println(ex);
}
}
}
Make sure that the InputStream is not closed within the loop.

Related

Issues with learning try/catch

I'm currently in a java course and trying to learn how to catch exceptions. In this case I have an input file that is only allowed to contain certains signs and must contain a goal and a start. I check all this in a seperate class constructor and want to insted of just telling the user something is wrong use a try/catch to tell the user that he did something wrong.
while(scanner.hasNext()){
temp = scanner.nextLine();
try {
testString(temp);
}
catch (/*Don't know what to catch*/){
System.out.println("Input file contains unvalid input");
}
mazeData.add(row, temp);
row++;
}
try{
containStartAndGoal();
}
catch(/*Dont know what to catch?*/){
System.out.println("Input file have either no goal or start!");
}
Currently this is my issue, i have tried to use a IOExecption but that does not seem to work. If I use just Execption i need to catch it every time i try to call this method. Which I do in both my test program and main program. I have tried to read as much as I can around here but don't seem to understand what I am suppose to do. Can I not try something if I don't throw it somewhere else? And what type of execption am I suppose to use when there is an input file that is incorrect. We didn't really get any information around how these work in school only that they exist.

Unable to execute Java code in SciTE

I have written a sample code:
import java.util.Scanner;
public class abcd {
public static void main(String[] args) {
System.out.print("please enter a: ");
Scanner a = new Scanner(System.in);
String b = a.next();
System.out.println(b);
}
}
I am able to compile and execute this code via Ubuntu terminal. In SciTe, it compiles fine, but when I run it, I am faced with this error:
please enter a: Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at abcd.main(abcd.java:8)
Any Suggestions?
EDIT: When I execute a file in terminal, I do: 'java abcd' Scite does: 'java -cp .abcd'. How are the two commands different and why isn't java -cp working?
It appears that there is a bug/improper implementation in the handling of standard input in SciTE on Linux/Unix.
The description of the bug and a workaround are in this PDF document: A Problem with SciTE Go Command on Linux
Note: this is not official documentation, but it seems to match your problem.
According to that document, when running a Java program through the "Go" command on SciTE, input is supposed to come from the output pane. However, on Linux this does not work properly, and it's as if you are reading from an empty stream.
When you are reading from an empty stream, Scanner sees the end-of-file marker when it attempts to read a value using next(), nextInt() etc. And it throws a NoSuchElementException as there is no input element in the stream.
Your options to work around this problem:
Try the method mentioned in the aforesaid document, to use "Go" in a Linux terminal instead of the output pane.
Run the program in a terminal and avoud the "Go" command altogether.
Use a different IDE which doesn't have this problem.
Try to use hasNext() before next();
import java.util.Scanner;
public class abcd {
public static void main(String[] args) {
System.out.print("please enter a: ");
Scanner a = new Scanner(System.in);
while(a.hasNext()) {
try {
String b = a.next();
System.out.println(b);
} catch (NoSuchElementException e) {}
}
}
}
I don't mean to offend, but using hasNext() as suggested in Alexander's answer won't solve this problem, it will only enable OP to handle it well. I don't think that is what he/she is looking for.
Now I am no expert by any means and for some reason your program code works on my machine... But anyways, a NoSuchElementException is thrown when your program is cycling over an iterable object and there is nothing more to cycle over, despite your program expecting something there. A quick look-up in the Java-docs of Scanner.next()
shows that this exception is thrown if there are no more tokens available for read.
Now, if I had to guess I would advise you to try using something other than Scanner.next() and see if that works.
The fact that it works on my machine but not on yours is somewhat surprising, so could you provide some information on how you try to run your program? Are you running it from the default command-line? Or within Scite? (If second is the case, I really won't be able to help you, I have never even touched Scite).

cannot find file for createNewFile

I'm writing a private method in Java that reads and write to a simple text file, which it should make if it doesn't exist since createNewFile() checks for that first.
private boolean updateGameQuota(String name, String quantity) {
...
File quotaLog = new File("seller-quotas.txt");
quotaLog.createNewFile();
...
return ret;
}
The compile-time error is: SmsFunctions.java:256: error: unreported exception IOException; must be caught or declared to be thrown
quotaLog.createNewFile();
^
1 error
Placing it in a try-catch block doesn't seem to be the issue, as I tried that (also on many other lines that try passing quotaLog) but eventually I get to a point where it's clear that something else is wrong. The File object is fine, but then if I try to use createNewFile or say
FileReader sQReader = new FileReader(quotaLog);
I get a FileNotFoundException even though the file is definitely there and I tried this on other text files which are read elsewhere successfully with the same result.
Any help or ideas would be greatly appreciated!
Update:
So in the end my issue was indeed just putting try-catch blocks around everything and making sure variables set within them were first created outside of those blocks. My confusion came from a false sense of sureness that fileraders/filewriters shoulnd't need try catch blocks (I could swear I've used them without many times) and the error was actually an indication of something else.
Perhaps before closing the thread someone could elaborate as to why Java doesn't always make a fuss about it, if that's true?
Thanks!
File.createNewFile() can throw an IOException (a checked exception) and needs to be surrounded in a try-catch block or the method you're using it in needs to be declared as throws IOException and you need to handle it upstream.
To debug the FileNotFoundException, you could try:
File quotaLog = new File("seller-quotas.txt");
System.out.println(quotaLog.getAbsolutePath());
Which uses the File.getAbsolutePath() method to print where it expects the file to exist.

When should I use an exception in java

I was trying to understand why to use exceptions.
Suppose if I have an program,
(without using try/catch)
public class ExceptionExample {
private static String str;
public static void main(String[] args) {
System.out.println(str.length());
}
I got exception
Exception in thread "main" java.lang.NullPointerException
at com.Hello.ExceptionExample.ExceptionExample.main(ExceptionExample.java:22)
Now using try/catch,
public class ExceptionExample {
private static String str;
public static void main(String[] args) {
try {
System.out.println(str.length());
} catch(NullPointerException npe) {
npe.printStackTrace();
}
}
}
I got Exception,
java.lang.NullPointerException
at com.Hello.ExceptionExample.ExceptionExample.main(ExceptionExample.java:9)
Now my question is,
In both the cases I have got the same message printed. So what is the use of using try/catch? and
What can we do after catching exception, in this case I have printed the stack trace. Is catch used only for printing the trace or for finding exception details using getMessage() or getClass()?
The difference is pretty big, actually.
Take the first one and add a line after the print:
public class ExceptionExample {
private static String str;
public static void main(String[] args) {
System.out.println(str.length());
System.out.println("Does this execute?");
}
}
You'll see that Does this execute? isn't printed because the exception interrupts the flow of the code and stops it when it isn't caught.
On the other hand:
public class ExceptionExample {
private static String str;
public static void main(String[] args) {
try {
System.out.println(str.length());
} catch(NullPointerException npe) {
npe.printStackTrace();
}
System.out.println("Does this execute?");
}
}
Will print both the stack trace and Does this execute?. That's because catching the exception is like saying, "We'll handle this here and continue executing."
One other remark, the catch block is where error recovery should happen, so if an error occurs but we can recover from it, we put the recovery code there.
Edit:
Here's an example of some error recovery. Let's say we have a non-existent file at C:\nonexistentfile.txt. We want to try and open it, and if we can't find it, show the user a message saying it's missing. This could be done by catching the FileNotFoundException produced here:
// Here, we declare "throws IOException" to say someone else needs to handle it
// In this particular case, IOException will only be thrown if an error occurs while reading the file
public static void printFileToConsole() throws IOException {
File nonExistent = new File("C:/nonexistentfile.txt");
Scanner scanner = null;
try {
Scanner scanner = new Scanner(nonExistent);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException ex) {
// The file wasn't found, show the user a message
// Note use of "err" instead of "out", this is the error output
System.err.println("File not found: " + nonExistent);
// Here, we could recover by creating the file, for example
} finally {
if (scanner != null) {
scanner.close();
}
}
}
So there's a few things to note here:
We catch the FileNotFoundException and use a custom error message instead of printing the stack trace. Our error message is cleaner and more user-friendly than printing a stack trace. In GUI applications, the console may not even be visible to the user, so this may be code to show an error dialog to the user instead. Just because the file didn't exist doesn't mean we have to stop executing our code.
We declare throws IOException in the method signature instead of catching it alongside the FileNotFoundException. In this particular case, the IOException will be thrown here if we fail to read the file even though it exists. For this method, we're saying that handling errors we encounter while reading the file isn't our responsibility. This is an example of how you can declare an irrecoverable error (by irrecoverable, I mean irrecoverable here, it may be recoverable somewhere further up, such as in the method that called printFileToConsole).
I accidentally introduced the finally block here, so I'll explain what it does. It guarantees that if the Scanner was opened and an error occurs while we're reading the file, the Scanner will be closed. This is important for many reasons, most notably that if you don't close it, Java will still have the lock on the file, and so you can't open the file again without exiting the application.
There are two cases when you should throw an exception:
When you detect an error caused by incorrect use of your class (i.e. a programming error) throw an instance of unchecked exception, i.e. a subclass of RuntimeException
When you detect an error that is caused by something other than a programming error (invalid data, missing network connectivity, and so on) throw an instance of Exception that does not subclass RuntimeException
You should catch exceptions of the second kind, and not of the first kind. Moreover, you should catch exceptions if your program has a course of action to correct the exceptional situation; for example, if you detect a loss of connectivity, your program could offer the user to re-connect to the network and retry the operation. In situations when your code cannot adequately deal with the exception, let it propagate to a layer that could deal with it.
try/catch will prevent your application from crashing or to be precise- the execution will not stop if an unintentional condition is met. You can wrap your "risky" code in try block and in catch block you can handle that exception. By handling, it means that do something about that condition and move on with execution.
Without try/catch the execution stopped at the error-making-line and any code after that will not be executed.
In your case, you could have printed "This was not what I expected, whatever, lets move on!"
Let's say you are connected to database but while reading the records, it throws some exception. Now in this particular case, you can close the connection in Finally block. You just avoided memory leak here.
What I meant to say is , you can perform your task even if exception is thrown by catching and handling it.
In the example you've given, you're right, there is no benefit.
You should only catch an exception if either
You can do something about it (report, add information, fix the situation), or
You have to, because a checked exception forces you to
Usual "handling" of an exception is logging the situation to a log file of your choosing, adding any relevant context-sesitive information, and letting the flow go on. Adding contextual information benefits greatly in resolving the issue. So, in your example, you could have done
public static void main(String[] args) {
try {
System.out.println(str.length());
} catch(NullPointerException npe) {
System.err.println(
"Tried looking up str.length from internal str variable,"
+" but we got an exception with message: "
+ npe.getMessage());
npe.printStackTrace(System.err);
}
}
when looking a message like that, someone will know based on the message what went wrong and maybe even what might be done to fix it.
If you are using Exception, don't
catch(NullPointerException npe) {
npe.printStackTrace();
}
simply
catch(NullPointerException npe) {
//error handling code
}
You are menat to remove error printing. And anyways catch general exception not just specific ones.
If you look at the two exceptions, they are actually different. The first one is referring to line 22, while the second one is referring to line 9. It sounds like adding the try/catch caught the first exception, but another line of code also threw an exception.
Consequently, the exception is being thrown because you never created a new String, or set a value to the string, unless it was done in a part of the code that is not shown.
Adding a try/catch block can be very helpful with objects that you have little to no control over, so if these objects are other than expected (such as null), you can handle the issue properly.
A string is normally something that you would instantiate first, so you shouldn't normally have to worry about using a try/catch.
Hope this helps.
To answer your original question Che, "when to use an exception?"
In Java - I'm sure you've already found out... There are certain methods in Java that REQUIRE the try / catch. These methods "throw" exceptions, and are meant to. There is no way around it.
For example,
FileUtils.readFileToString(new File("myfile.txt"));
won't let you compile until you add the try/catch.
On the other hand, exceptions are very useful because of what you can get from them.
Take Java Reflection for example...
try { Class.forName("MyClass").getConstructor().newInstance(); }
catch ( ClassNotFoundException x ) { // oh it doesnt exist.. do something else with it.
So to answer your question fully -
Use Try/Catch sparingly, as it's typically "frowned on" to EXPECT errors in your application.. on the contrary, use them when your methods require them.

Eclipse's Dead Code warning when it is reachable?

Why Eclipse gives me a dead code warning in the fourth line of the following method? How can it not be reachable?
private void writeToSequenceFile() {
try {
CustomFileWriter nBatchWriter = new CustomFileWriter(sequeneceFileName, CONFIG_RESOURCE_NAME, "outputFile");
// The line below is a dead code?
lineBuilder.setString("Line", fileSequenceDate.concat(" ").concat(fileSequenceNo));
lineBuilder.setString("LineFeed", "\r");
nBatchWriter.writeRecord(lineBuilder.toRecord());
nBatchWriter.close();
} catch (Exception ex){
throw new NcoBusinessProgramException("Error Writing To Sequence File!");
}
}
Does it compile?
The only possible way that I can imagine for that line to be unreachable would be if the CustomFileWriter constructor called writeToSequenceFile(), causing infinite recursion, so the next line would never be reached. (Or if the constructor always threw an exception, but that would be a pretty silly way to write it.)
Are you sure it is ? It might be an artefact, try to close and reopen the file, or save all and rebuild.

Categories