Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to catch exception generated by user inputting number over declared data of type int?  RSS feed

 
Ryan Jammes
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys, newbie here reading Head First Java, 2nd Edition, and am currently on pg. 41.

Anyway, i kind of went off on my own a bit and setup a very simple/basic calculator just to mess around a bit.

Below is a snippet of code. I decided i wanted to see if i could figure out how to handle the exception that is thrown when i or a user input a value above or below the maximum value data type 'int' can store. I googled and tried things for hours, but here i am. One of the first things i tried was like checking the value of the variable with an if statement. Of course i soon realized the exception was being thrown because i was trying to store a number higher than what data type 'int' can store.

How would i catch this so the program won't end? Is there a way to catch the exception with a 'int aVariable;' declaration, or do i have to try using something else like Integer()?




How i tried to fix it before i realized what the actual problem was.. I am curious though. Would there be a way to make something like this work for this problem?..


 
Knute Snortum
Sheriff
Posts: 4073
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch!

What if you stored num1 in a type bigger than an int?

Something you might not know: the minimum and maximum values for an int are stored in the class Integer.

Also, a note on your code: break long lines up so that the longest line is 80 to 100 characters.
 
Carey Brown
Bartender
Posts: 2992
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could put a try/catch block around
num1 = user_input.nextInt();
 
Campbell Ritchie
Marshal
Posts: 55694
163
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan Jammes wrote:. . .I am curious though. Would there be a way to make something like this work for this problem?..


No.

The nextInt method returns a number ≥−2147483648 and ≤2147483647. So the if loop you have will only return true under very specialised circumstances caused by inappropriate use of integer literals. Don't write 2147483647; write Integer.MAX_VALUE. You can also use Integer.MIN_VALUE. Look very closely at your code and the values of max value and min value (use the constant values link). So that if statement can never find an incorrect value for any int.

There is an alternative technique which Rob Spoor taught me. This sort of loop is best put into its own method in a utility class:-Line 1 tests for correct incorrect input; if what follows is incorrect input, then line 3 prints an error message and line 4 consumes the offending “token”, doing nothing with it. Some people would use System.out rather than System.err. You can swap lines 4 and 3. Line 6 finds the first non‑incorrect token (now there's some good English grammar!) and converts it to an int.

And welcome to the Ranch
 
Campbell Ritchie
Marshal
Posts: 55694
163
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Integer literals:
These are sometimes called magic numbers. A number like 12 appears in your code. What does it mean? Is it eggs in box? Inches in foot? Months in year? What happens if you change to boxes of ten eggs each? Which 12s do you change? How do you know you have got the right number for everything? How do you know one of them oughtn't to read 11 or 13? How do you know you haven't miscounted something by 1 (as you did earlier)? Those numbers can be error‑prone, too.
What you should do is declare constants:-Now if you ever change one of those constants, as long as it is marked private, you only need to change 1 place. If your constants are not private, then:-
Once a constant, always a constant.
If you change a public constant which is a compile‑time constant, then there is a risk that some code will retain the old value; you can even have different values in different classes in the same application. So a public compile‑time constant should retain the same value for ever.
 
Ryan Jammes
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Knute Snortum wrote:Welcome to the Ranch!

What if you stored num1 in a type bigger than an int?

Something you might not know: the minimum and maximum values for an int are stored in the class Integer.

Also, a note on your code: break long lines up so that the longest line is 80 to 100 characters.



Hi, yeah i could do that but i am trying to learn how to handle the exception/problem, unless you are saying that it is impossible?
 
Ryan Jammes
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Knute Snortum wrote:Welcome to the Ranch!

What if you stored num1 in a type bigger than an int?

Something you might not know: the minimum and maximum values for an int are stored in the class Integer.

Also, a note on your code: break long lines up so that the longest line is 80 to 100 characters.


Yeah i didn't know, i am brand spanking new and still find it pretty hard to read and understand the java docs. Thanks for the line length recommendation btw.
 
Ryan Jammes
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Carey Brown wrote:You could put a try/catch block around
num1 = user_input.nextInt();


Hi there, thanks. I had seen the try/catch block thing while googling but i didn't think about trying it around the input itself. That is definitely something i am going to try and need to learn about.
 
Ryan Jammes
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:
Ryan Jammes wrote:. . .I am curious though. Would there be a way to make something like this work for this problem?..


No.

The nextInt method returns a number ≥−2147483648 and ≤2147483647. So the if loop you have will only return true under very specialised circumstances caused by inappropriate use of integer literals. Don't write 2147483647; write Integer.MAX_VALUE. You can also use Integer.MIN_VALUE. Look very closely at your code and the values of max value and min value (use the constant values link). So that if statement can never find an incorrect value for any int.

There is an alternative technique which Rob Spoor taught me. This sort of loop is best put into its own method in a utility class:-Line 1 tests for correct incorrect input; if what follows is incorrect input, then line 3 prints an error message and line 4 consumes the offending “token”, doing nothing with it. Some people would use System.out rather than System.err. You can swap lines 4 and 3. Line 6 finds the first non‑incorrect token (now there's some good English grammar!) and converts it to an int.

And welcome to the Ranch



Hey ritchie, thanks very much. I enjoyed your informative replies and have read through them a couple times. I appreciate the recommendations and explanations, and i am gonna re-read them tomorrow and mess about with what you have suggested after i rest up a bit. Thanks again.
 
Knute Snortum
Sheriff
Posts: 4073
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan Jammes wrote:
Knute Snortum wrote:What if you stored num1 in a type bigger than an int?

Hi, yeah i could do that but i am trying to learn how to handle the exception/problem, unless you are saying that it is impossible?

No, it's not impossible. Take a look at Scanner#nextInt(). It throws an InputFormatException in the case you are interested in. Throw a try/catch block around the getInt() call and see what you get. (Test all kinds of input.)
 
Campbell Ritchie
Marshal
Posts: 55694
163
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Rob taught me ages ago, there is no need to mess around with Input Mismatch Exceptions. The loop I showed you a couple of days ago will reliably obviate any risk of that exception.

And sorry for delay in replying.
 
Ryan Jammes
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:As Rob taught me ages ago, there is no need to mess around with Input Mismatch Exceptions. The loop I showed you a couple of days ago will reliably obviate any risk of that exception.

And sorry for delay in replying.


No worries about they delay. I understand that, but i should still (and want to) learn about these things. I have run into a new issue and cannot figure out how to resolve it. The following code produces an infinite loop of:
1>Enter the first Number.
2>Try again. Input must be a valid 32-bit integer.

(Of course if you have any new critique of the following code that you wish to share, i would very much love to hear that as well!)


 
Ryan Jammes
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Knute Snortum wrote:
Ryan Jammes wrote:
Knute Snortum wrote:What if you stored num1 in a type bigger than an int?

Hi, yeah i could do that but i am trying to learn how to handle the exception/problem, unless you are saying that it is impossible?

No, it's not impossible. Take a look at Scanner#nextInt(). It throws an InputFormatException in the case you are interested in. Throw a try/catch block around the getInt() call and see what you get. (Test all kinds of input.)


I have run into a new issue and am wondering if you can help me out. The code should be in the comment above this one. [Don't want to re-paste/spam too much ]

Also my thinking is that this is happening because the stored int value should still be higher then the valid int max/min? I have tried setting some things to 0 but obviously i must not be doing this correctly.. i am really at a loss here, but i understand that it is probably something very simple that i am just missing because of my inexperience.
 
Knute Snortum
Sheriff
Posts: 4073
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to "flush the buffer" when you get an InputMismatchException. In the first catch block you need a line like this:

This will consume the rest of the input.

You have all of your code in main(). Create methods, get an instance of SimpleCalc in main() and call your driving method. Basically, nothing should be in main but a few lines of code to start things going.

What do you think user_input.equals(0); // Where i left off is doing?

The naming convention for user_input would be userInput.

You have two pieces of code doing almost the same thing (Input number 1 and 2). Put those in one method.
 
Ryan Jammes
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Knute Snortum wrote:
What do you think user_input.equals(0); // Where i left off is doing?


I was shooting in the dark to see if i could fix it, my thinking at the time was that the problem was that the stored int was still higher than the valid number for int, so i was trying to set everything that i could think of to 0 to see if it might continue on.

Knute Snortum wrote:
You have all of your code in main(). Create methods, get an instance of SimpleCalc in main() and call your driving method. Basically, nothing should be in main but a few lines of code to start things going.


I am currently starting on objects in the book, so i'll do that as soon as i can.
 
Knute Snortum
Sheriff
Posts: 4073
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan Jammes wrote:
Knute Snortum wrote:
What do you think user_input.equals(0); // Where i left off is doing?


I was shooting in the dark to see if i could fix it, my thinking at the time was that the problem was that the stored int was still higher than the valid number for int, so i was trying to set everything that i could think of to 0 to see if it might continue on.

Usually it's not a good idea to shoot in the dark. Trying something that does the same thing but differently it better. The equals() method for String takes another String and returns true if the two Strings are equal. It doesn't set anything.

Knute Snortum wrote:
You have all of your code in main(). Create methods, get an instance of SimpleCalc in main() and call your driving method. Basically, nothing should be in main but a few lines of code to start things going.


I am currently starting on objects in the book, so i'll do that as soon as i can.

You don't even need objects to write code with several methods. When you write a Class (which you will create your objects from) you should use more than one method.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!