If you are writing a switch statement that takes in a scanner type, how do you prevent a runtime error if a string or char is entered.

Scanner s = new Scanner(System.in);
int a;
a = s.nextInt();

switch(a){
}

So if i ran the code and entered "abc" then i would get an error. I would rather it just tell me that it the input was invalid and ask for the input again.

if you need it to accept both letters/#'s change your code to a string, not an int.
cheers'
Jamesonh20

In addition to Jamesonh20's suggestion, you should wrap the input routine in a while loop.

The while loop would exit once you have retrieved a correct value from the user.

The switch statement doesnt accept strings.

and there is a while loop in the source code, i just chose not to display it in the sample.

Edited 6 Years Ago by supersoup: n/a

You can simply use hasNextInt() to determine if there is one in the input. If there isn't then I believe it will continue gracefully.

...
So if i ran the code and entered "abc" then i would get an error. I would rather it just tell me that it the input was invalid and ask for the input again.

Since code isn't your thing.. here is some psuedocode:

set valid input false

while (not valid input) 
do
  prompt user for input value.
  get input value from user.
  if input value is what you are looking for 
    set valid input true
  else
    display error message
end

That is the logic that you are looking for. Try wrapping some code to it.

Since code isn't your thing.. here is some psuedocode:

set valid input false

while (not valid input) 
do
  prompt user for input value.
  get input value from user.
  if input value is what you are looking for 
    set valid input true
  else
    display error message
end

That is the logic that you are looking for. Try wrapping some code to it.

I'm just going to add a bit of extra coding that would make your code much less vulnerable to error:

set valid input false

while (not valid input) 
do
  try
    prompt user for input value.
    get input value from user.
    if input value is what you are looking for 
      set valid input true to break from loop
    else
      display error message
  catch any error that occurs
    perform this action
end

You might want to look up the try-catch statement if you don't already know it. It is uber useful for this input stuff. Try to implement this code and see how it goes.

Edited 6 Years Ago by kvass: n/a

System.out.println("Enter an int");
while (!scanner.hasNextInt()){
String tossThis = scanner.nextLine();
System.out.println("Enter an int");
}
int myInt = scanner.nextInt();

Just use this piece of code. There are other ways to force the user to input an int, but this will work.

This article has been dead for over six months. Start a new discussion instead.