• Post Reply Bookmark Topic Watch Topic
  • New Topic

Need help with Exception Handling  RSS feed

 
Buda young
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(NumberFormatException) Listing 9.5, Calculator.java, is a simple command-line calculator. Note that the program terminates if any operand is nonnumeric. Write a program with an exception handler that deals with nonnumeric operands; then write another program without using an exception handler to achieve the same objective. Your program should display a message that informs the user of the
wrong operand before exiting (see the figure shown below).

c:\exercise>java Exercise14_01 "4 + 5"
4 + 5 = 9

c:\exercise>java Exercise14_01 "4 - 5"
4 - 5 = -1

c:\exercise>java Exercise14_01 "4x - 5"
Wrong Input: 4x

c:\exercise>_






so my issue is right here I've done a couple of things like toString and trying to convert num1 and num2 in to a string and back to int, but I can't get it to print out as a latter like for example 9k - 2 is wrong try again


what am I missing here


and now for the second part I need to make the same program but with out a try and catch which I did


but my issue here is I get a error when I type in a latter here is the error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "r" /* I typed in 9 - r*/
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at NFE2.Calculator.main(Calculator.java:19)

what am I doing wrong here
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Buda young wrote:

c:\exercise>java Exercise14_01 "4 + 5"
4 + 5 = 9

c:\exercise>java Exercise14_01 "4 - 5"
4 - 5 = -1

c:\exercise>java Exercise14_01 "4x - 5"
Wrong Input: 4x



Am I right in thinking that this is sample input to your program provided by your teacher, along with the expected output?



Buda young wrote:



If my previous assumption was correct, then this program does not meet the interface specification that was provided in those example. You need to pass your program a single String containing the mathematical expression as a command line paramter and then evaluate it. Your program appears to be asking the user to enter the numbers individually, followed by the operator. I don't think you should be using the Scanner at all here.


so my issue is right here I've done a couple of things like toString and trying to convert num1 and num2 in to a string and back to int, but I can't get it to print out as a latter like for example 9k - 2 is wrong try again

Buda young wrote:



I'm not sure what you're trying to achieve with your exception handler. You create an array with a length equal to the number the user entered (or zero if they didn't enter an int). You don't put anything in the array, and then for each element in the array your print out the entire array and say it can't be compared to num2. What was your intention here?



Buda young wrote:
and now for the second part I need to make the same program but with out a try and catch which I did


but my issue here is I get a error when I type in a latter here is the error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "r" /* I typed in 9 - r*/
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at NFE2.Calculator.main(Calculator.java:19)

what am I doing wrong here


This program also doesn't appear to meet the interface requirements specified above. You don't have an exception handler, but I think the implied requirement was that your program should not throw any Exceptions if the user enters something non-numeric. You also aren't getting the input from the commandline parameter like the example was. I don't think you should be using the Scanner, and I think you should be validating the input in such a way that no Exception is thrown if the input is not a valid arithmetical expression.
 
Buda young
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mike. J. Thompson wrote:
Buda young wrote:

c:\exercise>java Exercise14_01 "4 + 5"
4 + 5 = 9

c:\exercise>java Exercise14_01 "4 - 5"
4 - 5 = -1

c:\exercise>java Exercise14_01 "4x - 5"
Wrong Input: 4x


Am I right in thinking that this is sample input to your program provided by your teacher, along with the expected output?


yes it is



Buda young wrote:





I dont think my teachers main concern is the layout. I see he want to see if we can actually make a running and work program seeing that this is a intro to java. now about Scanner, Scanner is the only thing we have learned to use in the class.



If my previous assumption was correct, then this program does not meet the interface specification that was provided in those example. You need to pass your program a single String containing the mathematical expression as a command line paramter and then evaluate it. Your program appears to be asking the user to enter the numbers individually, followed by the operator. I don't think you should be using the Scanner at all here.




so my issue is right here I've done a couple of things like toString and trying to convert num1 and num2 in to a string and back to int, but I can't get it to print out as a latter like for example 9k - 2 is wrong try again

Buda young wrote:



this was just me trying out things to see if it would work I originally had


I'm not sure what you're trying to achieve with your exception handler. You create an array with a length equal to the number the user entered (or zero if they didn't enter an int). You don't put anything in the array, and then for each element in the array your print out the entire array and say it can't be compared to num2. What was your intention here?



Buda young wrote:
and now for the second part I need to make the same program but with out a try and catch which I did


but my issue here is I get a error when I type in a latter here is the error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "r" /* I typed in 9 - r*/
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at NFE2.Calculator.main(Calculator.java:19)

what am I doing wrong here



again All I know is scanner and the teacher is just looking to see if we can make a program run and handle the exception with out a try and catch I was trying the num1.match([0-9]) like this this but this give me an error java.lang.NumberFormatException ??? I see nothing wrong with line 15 int i = Integer.parseInt(num1);

This program also doesn't appear to meet the interface requirements specified above. You don't have an exception handler, but I think the implied requirement was that your program should not throw any Exceptions if the user enters something non-numeric. You also aren't getting the input from the commandline parameter like the example was. I don't think you should be using the Scanner, and I think you should be validating the input in such a way that no Exception is thrown if the input is not a valid arithmetical expression.

 
Tony Docherty
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All I know is scanner and the teacher is just looking to see if we can make a program run and handle the exception with out a try and catch I was trying the num1.match([0-9]) like this this

You can't handle the excpetion without a try-catch clause. The try-catch clause is Java's exception handling mechanism.
I suspect, as Mike said earlier, you are required to do some validation on the input before converting it to a number to prevent the conversion from throwing an exception.
 
Buda young
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok my teacher just sent us an email saying to ignore part two of the assignment. now I need to just figure out how to display the error message on part one.


Ok I belive I got it I'm sure some of you will say my code looks ugly so now I guess can you give me some pointers on cleaning it up

 
Rico Felix
Ranch Hand
Posts: 411
5
IntelliJ IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Analysing the code you've provided in your last post, the application seems logically correct.

To clean up the implementation you can follow the following steps:

1. Remove the irrelevant java.util.* import statement since you are only using the Scanner class from that package
2. Declare and initialize the Scanner class just before the String num1 variable so it can be accessed throughout the main method, that way you will only need to use that one instance for user input since it will be in scope for the entire main method. Therefore you can remove all the instances sprinkled about in the code.
3. Remove the parsing statements in the else block located in the try block located in the do-while loop only leaving the break statement. This recommendation is due to redundancy in the loop and after the loop.
4. Checking for the operation it will be better to use else if statements instead of independent if statements, that way you can provide an else statement at the tail of the chain to provide feedback if they chose an invalid option. (there is also the switch statement)
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you have the requirements of part 1 and part 2 combined by mistake in your latest effort. Part 1 says that you should use exception handling to handle the case where the user enters invalid input, but you are attempting to manually validate the input. If you correctly validate the input then there will be no exception thrown even when the user enters the invalid data.

However your attempt at validating the input is not quite sufficient. What will happen if the user enters '[' for num1, or '£' for num2 for example?

I suspect the reason you are having trouble with printing the error message is because your loop starts again if you enter a letter. Remove the validation completely and just attempt to parse the number. That way the Exception will be thrown and your catch block will execute.
 
Janeice DelVecchio
Bartender
Posts: 1812
12
Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The program would be a whole lot easier passing args from the command line as in the directions for the assignment. You wouldn't need scanner, or a loop or all that user interface malarkey and having to think about someone using it wrong. You'd have the args in the String[] and it'd be WAY easier because you either have three arguments (first number, operator, second number) or not, and the validation would be far easier.

How to get information from the command line
 
Buda young
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mike. J. Thompson wrote:I think you have the requirements of part 1 and part 2 combined by mistake in your latest effort. Part 1 says that you should use exception handling to handle the case where the user enters invalid input, but you are attempting to manually validate the input. If you correctly validate the input then there will be no exception thrown even when the user enters the invalid data.

However your attempt at validating the input is not quite sufficient. What will happen if the user enters '[' for num1, or '£' for num2 for example?

I suspect the reason you are having trouble with printing the error message is because your loop starts again if you enter a letter. Remove the validation completely and just attempt to parse the number. That way the Exception will be thrown and your catch block will execute.



well the teacher never asked to for an exception for the operation, but i guess he didn't say we can't i will add it i just far getting a lower grade. he once gave me a low grade on a project for adding a GUI.
 
Buda young
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Janeice DelVecchio wrote:The program would be a whole lot easier passing args from the command line as in the directions for the assignment. You wouldn't need scanner, or a loop or all that user interface malarkey and having to think about someone using it wrong. You'd have the args in the String[] and it'd be WAY easier because you either have three arguments (first number, operator, second number) or not, and the validation would be far easier.

How to get information from the command line


you guy keeps saying stop using Scanner and use a some type of validation but we never learn about validation. I'll look it up and all the malarkey is all I know for now and I can't use a interface he didn't say to use one last time i tried going making the project nice looking with a gui I got a lower grade for not following instruction.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Buda young wrote:I got a lower grade for not following instruction.

In that case you definitely shouldn't be using a Scanner - based on the example you showed in your first post, the program should accept a single command line argument (you can access this using args[0] in your main method). You then need to split that single argument into three (use String.split() to do this) and you then need to validate the three tokens you have - the first and third need to be numbers and the second one needs to be an operation (+, -, *, /).
So the first thing you do should be to write a simple program that accepts a single command line argument and prints it out. Don't worry about validation or anything else for the moment. It should have only one line of code in the main method.
Get that working first before you even think about the next step.
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Buda young wrote:
Janeice DelVecchio wrote:The program would be a whole lot easier passing args from the command line as in the directions for the assignment. You wouldn't need scanner, or a loop or all that user interface malarkey and having to think about someone using it wrong. You'd have the args in the String[] and it'd be WAY easier because you either have three arguments (first number, operator, second number) or not, and the validation would be far easier.

How to get information from the command line


you guy keeps saying stop using Scanner and use a some type of validation but we never learn about validation. I'll look it up and all the malarkey is all I know for now and I can't use a interface he didn't say to use one last time i tried going making the project nice looking with a gui I got a lower grade for not following instruction.


No, we haven't said to use validation. You presented 2 exercises, one where you have to use exception handling to deal with invalid input and one where you don't use exception handling to deal with invalid input. The second of those exercises will require validation to avoid Exceptions.

However you have now been told to just concentrate on the first of those exercises; using Exception Handling. But the code that you posted as a solution was attempting to both perform validation and use Exceptions. For the first part of your exercise you need to remove the validation and just handle the Exception.

And I'm definitely with Joanne here. Your initial post contained example executions of your application. Each example passed a complete mathematical expression on the command line, and printed out the result of the value of the expression.

Before you write another line of code you need to sit down and work out what the requirements are, especially if your teacher is being strict about following the guidelines to the letter. Find out exactly what your program will take as input and exactly how you are expected to present the output. Until you know these things you can write all the code in the world and it may even work perfectly, but you could still end up getting marked down for doing the wrong thing.
 
Buda young
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you everyone
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that looks much better than before and it will be much more natural for a user of your program. Just two minor comments I would make:

Firstly the expression args.length == 0 || args.length != 3 has the same value as args.length != 3 for all values of args.length so the first half of the expression is redundant.

Secondly there is some repeated code in your switch statement. The call to System.out.println(...) is identical in each of your case statements. It's good practice (and generally leads to elegant code) if you minimise repeated code as much as possible. If you've learnt about them yet I would advise writing a method to print out the result.
 
Buda young
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mike. J. Thompson wrote:Yes, that looks much better than before and it will be much more natural for a user of your program. Just two minor comments I would make:

Firstly the expression args.length == 0 || args.length != 3 has the same value as args.length != 3 for all values of args.length so the first half of the expression is redundant.

Secondly there is some repeated code in your switch statement. The call to System.out.println(...) is identical in each of your case statements. It's good practice (and generally leads to elegant code) if you minimise repeated code as much as possible. If you've learnt about them yet I would advise writing a method to print out the result.



you mean like this
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!