Results 1 to 4 of 4
- 09-17-2012, 12:49 AM #1
Member
- Join Date
- Jul 2012
- Posts
- 93
- Rep Power
- 0
try catch statement and scanner variable
How do you access a scanner variable initialized inside of a try catch statement outside of it?
The num in the if statement can't see the keyb.nextInt value.Java Code:try { int num = keyb.nextInt(); } catch (java.util.InputMismatchException e) { System.out.println("Invalid input"); } if (num <= 0)
- 09-17-2012, 12:51 AM #2
Re: try catch statement and scanner variable
You need to define a variable at the scope level that it is used at.
You can give it a value in any nested scopes.
Define it outside of the {}s so all can see and use it.If you don't understand my response, don't ignore it, ask a question.
- 09-17-2012, 01:03 AM #3
Member
- Join Date
- Jul 2012
- Posts
- 93
- Rep Power
- 0
Re: try catch statement and scanner variable
How would you define
outside of the try catch statement without prompting the user to input an integer?Java Code:int num = keyb.nextInt();
- 09-17-2012, 01:31 AM #4
Re: try catch statement and scanner variable
You don't need to assign a value to a variable when you define it: int num; // define num
You can assign a value to a variable that is defined: num = 2; // assign value to num
Define num outside, assign it a value inside.If you don't understand my response, don't ignore it, ask a question.
Similar Threads
-
How can I put another word in the statement after i have inserted the variable
By Biscuit Tickler in forum New To JavaReplies: 2Last Post: 09-13-2012, 08:06 PM -
catch error statement
By droidus in forum New To JavaReplies: 11Last Post: 03-16-2012, 09:49 AM -
Not able to enter input with String variable set to Scanner
By atac57 in forum New To JavaReplies: 1Last Post: 01-30-2012, 04:41 AM -
try/catch and if statement conundrum
By thatguywhoprograms in forum New To JavaReplies: 4Last Post: 12-19-2011, 10:20 PM -
Scanner.next() within an if statement.
By ngc0202 in forum New To JavaReplies: 11Last Post: 08-12-2010, 12:26 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks