Jump to content

Hello guys, i just want to ask if there is any way to figure out this...
If i will have 

int a;

System.out.println("Type number 1 or 2 ");

a = sc.nextInt();

 

switch(a)

{

case 1:

something...

break;

 

case 2:

something...

break;

default:

something...

 

break;

}

 it doesnt metter what is inside "cases and default" but what i need to know how can i figure out the thing that when someone stupid (our teacher everytime try to crash our programm) will write 0,1 or something under a <0 ?  is there any possible wait to "fix it" 

I'm thinking about something like whe user types something < 0 the programm will "type" System.out.println("You need to type nuber 1 or 2")

Link to comment
https://linustechtips.com/topic/541891-switch-question/
Share on other sites

Link to post
Share on other sites

First, please use code tags when posting code on the forum.

 

To answer your question, if you're not allowed to assume that the input is always correct, then you can use a try/catch to handle what happens if a = sc.nextInt(); throws an exception.

Link to comment
https://linustechtips.com/topic/541891-switch-question/#findComment-7173387
Share on other sites

Link to post
Share on other sites

5 minutes ago, madknight3 said:

First, please use code tags when posting code on the forum.

 

To answer your question, if you're not allowed to assume that the input is always correct, then you can use a try/catch to handle what happens if a = sc.nextInt(); throws an exception.

First, sorry for that. 

And thank you so much! really good idea

 

Link to comment
https://linustechtips.com/topic/541891-switch-question/#findComment-7173476
Share on other sites

Link to post
Share on other sites

Correct java does not have that function. You could always create a tryparse method but you would be using the try and catch block within it. If you are going to need to parse multiple strings I would create the method. If you just need it for one string I would use the try/catch block.

Link to comment
https://linustechtips.com/topic/541891-switch-question/#findComment-7185340
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×