This question already has answers here:
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed 6 years ago.
Is there a way to handle the number(order) of NumberFormatException? I made a calculator using Double operand[], and like below, I want to write when did error occurred. When I put the input "2+k", the message saying that "operand[1] has the wrong input." should come out. How should I do like that?
First, replace the line
System.out.println("operand[] has the wrong input.");
with the line
System.out.println(e.getMessage());
Now you can pass a message when you throw the exception in the MyCalculator.calculate() method using the NumberFormatException(String) constructor. It would look something like this:
calculate(String expression)
{
//validate input code
//...
//if operand 0 not valid
throw new NumberFormatException("operand 0 has the wrong input");
//if operand 1 not valid
throw new NumberFormatException("operand 1 has the wrong input");
//rest of calculate method
}
Maybe you could define a new exception. As for example CalculatorException which could contain more specific information about calculations, as for example which operand is incorrect. Or you could even define one more exception like IllegalOperandException which could extend CalculatorException. And then your method calculate could be declared to throw a CalculatorException. In conclusion, the idea is to define a new hierarchy of exceptions to give information more related to the domain of your problem.
And then, your code could be so:
try {
System.out.println("result: " + MyCalculator.calculate(expression));
System.out.println();
} catch(CalculatorException e) {
System.out.println(e.getMessage());
}
Related
I have this code:
public static void main(String[] args) {
List<Valtozas> lista = new ArrayList<Valtozas>();
try {
File fajl = new File("c://data//uzemanyag.txt");
Scanner szkenner = new Scanner(fajl, "UTF8");
while (szkenner.hasNext()) {
String sor = szkenner.nextLine();
String [] darabok = sor.split(";");
String szoveg = darabok[0];
Valtozas valtozas = new Valtozas(Integer.valueOf(darabok[0]), Integer.valueOf(darabok[1]), Integer.valueOf(darabok[2]));
lista.add(valtozas);
}
}
catch (Exception e) {
}
//3.FELADAT
System.out.println("3.Feladat: Változások száma: "+lista.size());
}
}
Here I want to convert the String to int, but I cant. I tried the Integer.Valueof(darabok[0]), but its not working. And nothing is happening, so the code is build, but quit from the while.
Based on the source code you have shown us, the problem is that there is a format mismatch between the input file and the program you are trying to read.
The program reads the file a line at a time, and splits it into fields using a single semicolon (with no whitespace!) as the file separator. Then it tries to parse the first three fields of each split line as integers.
For this to work the following must be true:
Every line must have at least three fields. (Otherwise you will get a ArrayIndexOutOfBound exception.)
The three fields must match the following regex: -?[0-9]+ i.e. an optional minus signed followed by one or more decimal digits.
The resulting number must be between Integer.MIN_VALUE and Integer.MAX_VALUE.
Elaborating on the above:
Leading and trailing whitespace characters are not allowed.
Embedded decimals markers and grouping characters are not allowed.
Scientific notation is not allowed.
Numbers that are too large or too small are not allowed.
Note that if any of the above constraints is not met, then the runtime system will throw an exception. Unfortunately, you surround your code with this:
try {
...
}
catch (Exception e) {
}
That basically ignores all exceptions by catching them and doing nothing in the handler block. You are saying to Java "if anything goes wrong, don't tell me about it!". So, naturally, Java doesn't tell you what is going wrong.
DON'T EVER DO THIS. This is called exception squashing, and it is a really bad idea1.
There are two ways to address this:
Print or log the stacktrace; e.g.
catch (Exception e) {
e.printStackTrace();
}
Remove the try / catch, and add throws IOException to the signature of your main method.
(You can't just remove the try / catch because new Scanner(fajl, "UTF8") throws IOException. That's a checked exception so must be handled or declared in the method signature.)
Once you have dealt with the exception properly you will get an exception message and stacktrace that tells you what is actually going wrong. Read it, understand it, and fix your program.
1 - It is like taping over the "annoying" red light that indicates that your car's oil level is low!
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 an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 8 years ago.
I'm attempting to make a java function that returns an int inputted by the user, but won't return until the user inputs a valid number. Here's my initial model of the function:
public int getChoice(){
try{
return scan.nextInt();
}catch(Exception e){
return getChoice();
}
}
scan is declared by Scanner scan = new Scanner(System.in);
This function resulted in a Java.lang.stackOverflowError(hmm... this seems an appropriate website for that...). I figure this is because the function is being constantly called.
I've considered somehow using Integer.valueOf(scan.nextLine())', but the reason I haven't really done anything with it is because at some points, and I can't figure out what determines whether this happens or not, but pressing 'Enter' when the program is calling nextLine() will skip the next nextLine(). I can't really figure out a way around that.
So if anyone could possibly provide me with a Java function that will loop until the user inputs a valid integer, then return that integer, please do so, thank you.
You are getting a bad recursion because the getChoice call inside catch block. To repeat the code indefinitely until the user gives you a valid number use while(true) infinite loop. The code you have to read the line and convert it to Integer it is just fine.
public int getChoice() {
while (true) {
try {
return Integer.valueOf(scan.nextLine());
} catch (Exception e) {
System.out.println("Enter a valid number");
}
}
}
my application will have a text box which the user will edit with numbers (hopefully)
I am using Integer.parseInt() to convert the string into a integer, however, there's always the chance the user will not pass in numbers which will throw an exception during parseInt(). I am not sure what the convention is for error handling in GWT. Does this work?
int number = -1;
try {
number = Interger.parseInt(inputFromUser);
} catch (Exception e) {
// error handling like telling user to try again
}
If you want number-only boxes, use IntegerBox, LongBox, or DoubleBox. They already support rendering and parsing of, respectively, integer, long or double values using locale-aware renderers/parsers (based on NumberFormat).
You are on the right track. Just change Exception to NumberFormatException and you should be fine.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java: Try-Catch-Continue?
I'm reading in information from a text file and I want my code to throw an exception if there is an invalid type being read. However, I can't figure out how to have my program continue after an exception has been found
while(input.hasNext()) {
try{
type = input.next();
name = input.next();
year = input.nextInt();
} catch(InputMismatchException ex)
{
//System.out.println("** Error: Invalid input **");
//code to make program continue
}
}
You can either just let the thread leave the catch block - code execution will continue after that. If you want to skip the code after the catch block, you can use the continue keyword within a while loop...
If you want to retrieve a year after retrieving the name failed with an exception, then you will have to put a try ... catch around each input.next...() statement. You cannot restart execution at the point the exception has been thrown.