OK, here's my problem. Our teacher wants us to create a program that creates a Fibonacci sequence and then the user can do operation with the array of numbers (like get number at an index, etc). I wanted to go above and beyond and idiot-proof it. I asked her about try/catch statements but she said that it was not in the curriculum.So, I did research and made this code:
while( valid ) {
try {
lengthOfSequence = keyboard.nextInt();
} catch ( Exception e ) {
out.println( "You entered an " + e + ". Please enter a number between 1 and " + maxLength );
throw e;
}
}
(valid it true initially) So the code is supposed to get an integer that the user inputs. Then take that integer and assign it to lengthOfSequence. Running it properly (inputting an integer) will allow the code to run correctly, but when I plug in a "o" (or any other string) for my input, the catch is not catching the Exception and I get this error:
java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at FibonacciRunner.main(FibonacciRunner.java:28)
I've tried many ways to try to fix it including:lengthOfSequence = Integer.parseInt( keyboard.nextLine() ); which gives me
java.lang.NumberFormatException: For input string: "o"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at FibonacciRunner.main(FibonacciRunner.java:29)
I've also tried naming the exception InputMismatchExceptionand NumberFormatException but still I get an error.
I'm a novice at coding and at Stack Overflow, so thank you in advance for the help
EDIT:
I have tried removing the throw e but all that does is create an endless loop of the code outputting "You entered an java.util.InputMismatchException. Please enter a number between 1 and 101".
Also I removed this from the try statement because I thought it would not pertain to the question
if( lengthOfSequence > 1 && lengthOfSequence < maxLength ) {
fibonacci.createSequence( lengthOfSequence );
valid = false;
}
Change your code to:
boolean valid = false;
while( !valid ) {
try {
lengthOfSequence = keyboard.nextInt();
valid = true;
} catch ( Exception e ) {
out.println( "You entered a wrong value. Please enter a number between 1 and " + maxLength);
}
}
If you throw the exception, as you did in:
throw e;
Your program will no longer catch it and will suspend execution.
Remove throw e;, that's all you need to do. You have already caught the exception in the catch clause, if you throw it then your calling method would have to catch it again. But since the calling method does not have a try-catch mechanism, program will terminate and give you UNCAUGHT EXCEPTION
Titus answered my question as a comment but because I cant mark a comment as a question Ill just answer it myself:
This question is similar to: How to handle infinite loop caused by invalid input using Scanner
Quoting Titus:
to stop the loop when you receive bad input, you will have to consume that input in the catch block, you can do that by adding this statement in the catch block: keyboard.next() or keyboard.nextLine()
So I just added a keyboard.next(); to my catch block and removed the throw e and it stopped bugging out. Thank you guys!
Related
I have the following java code:
System.out.print("\fPlease Enter an integer: ");
while(!validInt){
try{
number = kb.nextInt();
validInt = true;
}catch(InputMismatchException e){
System.out.print("Pretty please enter an int: ");
System.out.print(e.getMessage());
kb.nextLine();
continue;
)
kb.nextLine();
}
how can I set e.getMessage() so that System.out.println(e.getMessage()) will print "Pretty please enter an int: "
You only set the message when the exception is created, it's an argument to the constructor. In your case it would have been nice if the InputMismatchException was created like this:
tnrow new InputMismatchException("Pretty please enter an int: ")
Since you probably aren't creating the InputMismatchException, you can't set it's message, however inside a catch you can do something liket this:
catch(InputMismatchException ime){
throw new IllegalArgumentException("Pretty please enter an int: ");
}
Then someone above you can catch that exception and will have an appropriate error message.
This is obviously a bit awkward which is why it usually isn't used this way.
Note:
You aren't usually supposed to re-use java exceptions but create your own. This is pretty annoying and I almost always re-use either IllegalArgumentException or IllegalStateException Because those are good, reusable exceptions and describe most of the reasons you'd want to throw in general code for "Catch and rethrow" exceptions as I discussed above.
Language: Java, IDE: eclipse mars
The program is supposed to prompt the user (using JOptionPane) for a positive value. I'm trying to catch the invalid entries. My while statement catches the negative numbers but not the strings. When a negative number is entered, the prompt is shown again, but when a string value is entered, the exception is caught and the program moves on (when it should re prompt the user).
Once a positive value has been entered, the program assigns it to a value in another class. (We're learning the MVC OOP design pattern).
Double.isNaN(Double.parseDouble(h)) ---> can anyone help me find what am I missing?
// prompt to get bandwidth from user
// check for validity
// if invalid, prompt again
try{
h = JOptionPane.showInputDialog("Enter bandwidth as a positive number");
// loop until parsed string is a valid double
while (Double.isNaN(Double.parseDouble(h)) || Double.parseDouble(h) <=0) {
h = JOptionPane.showInputDialog("Enter bandwidth as a positive number");
}
// h has been set to valid double, set it to bandwidth
model.setBandwidth(Double.parseDouble(h));
}catch(NumberFormatException|NullPointerException NFE){
System.err.println("Caught exception: " + NFE.getMessage());
}
This is because of how parseDouble() works.
Throws:
NumberFormatException - if the string does not contain a parsable double.
(See here)
So if the String is not a double parseDouble() will not return NaN but throw an exception, which means your catch clause will be called.
To solve this problem maybe use recursively algorithm which will call your method again if an exception is thrown.
As 4castle already stated, you need to move your try/catch block inside your while loop.
However, for validating user input you can basically stick to the following pattern:
public Foo getUserInput() {
Foo result;
do {
try {
String s = requestUserInput(); // something like Scanner.nextLine()
result = parseUserInput(s); // something like Double.parseDouble(String)
}
catch(Exception exc) {
// maybe you want to tell the user what's happened here, too
continue;
}
}
while(!isValid(result)); // something like (0 < result)
return result;
}
First post so my apologies if this was done incorrectly (and am also relatively new to programming, so any extraneous tips are also appreciated).
So I have written up a basic calculator program in Java. It works well currently, but I am having a particular issue with NumberFormatException. Here's the code:
private static double spaceTestAndConvert(String numInput){
Scanner input= new Scanner(System.in);
if (numInput.equalsIgnoreCase("quit")){
System.exit(1);
}
else if(numInput.equalsIgnoreCase("C/E")){
Restart();
}
try{
return Double.parseDouble(numInput.trim());
}
catch(NumberFormatException nfe){
numInput = "";
System.out.println("Please enter only one number without any spaces or letters: ");
numInput = input.nextLine();
spaceTestAndConvert(numInput.trim());
return Double.parseDouble(numInput.trim());
}
}
The issue is that after trying to force an error by entering in several inputs which would cause NumberFormatException and then entering in a valid input, the program will crash from a NumberFormatException citing the previous invalid input.
I.E. -
"1 2 3"
loops back
"1 2 q 3"
loops back
"12q3 3 sqw 1"
loops back
"12"
crash - Exception in thread "main" java.lang.NumberFormatException: For input string: "12q3 3 sqw 1"
It only occurs after several occurrences of the exception. I'm curious why it is doing this. Any advice on how to fix this or explanation of what is happening? If you need any other part of the code, please let me know! Thanks!
I don't follow everything that you're saying, but these 2 lines (from within your catch block) look problematic...
spaceTestAndConvert(numInput.trim());
return Double.parseDouble(numInput.trim());
You are calling the spaceTestAndConvert function recursively, but throwing away the value. I don't understand why you would call it and not be interested in the value.
The second line is also a mess. You so carefully surround the first call to Double.parseDouble() with try/catch, but then you call it again within your catch block. If the second Double.parseDouble() generates a NumberFormatException, it will not be caught.
removing the return in catch will solve your problem. because if you have return on it, you are going to return an invalid Number format since you are in a catch. What you want to do is to return a value when it is now valid, you are now actually doing it inside the try. Don't force your program to return the value with error (since it is in a catch) because it will really give you an error.
returning to previous method after you had the right value (because of recursion) will still have the stack of error value aside from success value you gained from the end part because they are different variables.
private static double spaceTestAndConvert(String numInput){
Scanner input= new Scanner(System.in);
if (numInput.equalsIgnoreCase("quit")){
System.exit(1);
}
else if(numInput.equalsIgnoreCase("C/E")){
Restart();
}
try{
return Double.parseDouble(numInput.trim());
}
catch(NumberFormatException nfe){
numInput = "";
System.out.println("Please enter only one number without any spaces or letters: ");
numInput = input.nextLine();
spaceTestAndConvert(numInput.trim());
}
}
This question already has answers here:
try/catch with InputMismatchException creates infinite loop [duplicate]
(7 answers)
Closed 7 years ago.
I really have no idea about this problem...
The block catches an exception if the number is not correct, when I put -1 or 0 it catches the Exception and asks me to input the number again... but if I type something like asdasd it will run an infinite loop.
while (true){
try{
System.out.println("-Size of the array: ");
size = read.nextInt();
if(size<=0){
throw new Exception();
}else{
break;
}
}
catch(Exception e){
System.out.println("\n-Wrong input. Try again.\n");
}
}
Probably the best way to deal with this is to change it so that reader gets the next line:
String input = read.nextLine();
if(input.length() == 0) { continue; }
try{
size = Integer.parseInt(input);
} catch(NumberFormatException e){ throw new Exception(); }
Put the Scanner initialization inside while loop:
while (true){
try{
Scanner read = new Scanner(System.in);
System.out.println("-Size of the array: ");
size = read.nextInt();
if(size<=0){
throw new Exception();
}else{
break;
}
}
catch(Exception e){
System.out.println("\n-Wrong input. Try again.\n");
}
}
My guess is that read.nextInt is throwing an exception because "asdasd" is not an integer. This will cause your exception handler to be run and print the message. However, because you don't have "break" in your exception handler, the loop will be run again... and again...
I suspect that you are getting caught out because you are throwing and catching Exception. If you add e.printStackTrace(); to the catch plock that you will probably find that you are catching an exception that you are not expecting to happen ... like one coming from the nextInt() call, or an NPE or something.
Don't throw Exception. Not ever. Use a specific exception, creating one for your self if none of the standard ones is appropriate.
Don't catch Exception unless you are prepared to deal with ALL of the possibilities. And that includes all of those unexpected unchecked exceptions that are due to random bugs in your code.
I have a java program that is supposed to handle an Exception, but the end result is far from what I intended it to be. Here is the overall idea of my program: it is supposed accept an input of zero and exit the program. The input dialog should cause an Exception which should be caught and print the message "bad number".
My brain is telling me I'm missing one line of code in the catch block.
here is my code:
import javax.swing.JOptionPane;
public class exceptTest {
public static void main(String[] args){
try {
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0"));
System.exit(0);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "bad number");
}
}
}
You are not catching an exception here, you are simply making a if statement, you can just use an if/else.
try{
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0")){
System.exit(0);
}else{
JOptionPane.showMessageDialog(null, "bad number");
}
}catch (Exception ex){
ex.printStackTrace();
}
The catch you would only use for any exceptions showInputDialog() throws, but for your number check you are not catching anything, it just simply is not 0.
You don't execute your exception handling code because you never throw an exception. The code will execute the input, then test the input to be equal to "0", then based on that will or will not display a dialog, and then it will execute.
The throwing of an exception occurs either because something has happened outside the conditions that the code will handle, or because you throw one explicitly.
By "outside the conditions" etc., I mean something like dividing by 0. Java (nor any other language) will handle that, and an exception will be thrown. The normal steps of procedural processing will stop, and an execution handler will be called.
In your case, if you (for instance) attempted to parse the input to be a number, but the input was not a number, you would get an exception. This is different functionality than you say you wanted, but is a better illustration of what an exception is for. Something like
try
{
int numberEntered = Integer.parse(line);
JOptionPane.showMessageDialog(null, "Entered a number, parsed to " + numberEntered);
}
catch (NumberFormatException nfe)
{
JOptionPane.showMessageDialog(null, "Did not enter a number, but <" + line + ">");
}
shows the sort of thing exceptions are normally good for.
If you wanted to, you could define an exception, call it BadNumberException, and throw it in the code you have -- you would put it (I guess) in an else clause for your if statement. But your routine would be throwing the exception, and I think it is unusual for the routine that throws an exception to also catch it.
Hope that helps.
rc
You have a semi-colon after your if statement, it terminates the line and the compiler does not look for the rest of the if. Remove your semi-colon and it will work fine.
import javax.swing.JOptionPane;
public class exceptTest
{
public static void main(String[] args){
try
{
String line = JOptionPane.showInputDialog(null, "enter number");
if(line.equals ("0")) //semi-colon removed here
{
System.exit(0);
}
throw new IllegalArgumentException("Input was not 0");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "bad number");
}
}
}
Your code does not throw an exception if the input is not equal to 0. Therefore, you never catch anything, thus no errormessage is shown on the screen.
You could do two things:
- throw an exception if the input is not 0 (then you will enter the catch)
or
- use an else with your if that displays the error message (then you don't need the try-catch for checking whether the input is 0)
Edit: And of course as Hunter McMillen noticed, you need to remove the semicolon after your if statement.