0

I am making a program and cannot figure out how to make my scanner input only recognize numbers. Here is what I mean.

System.out.print(" What is the distance in feet:" ); 
//ask the user to input variables 

Distance = keyboard.nextDouble(); 

What can I put after the distance input in order to allow me to output some sort of message telling the user they didn't enter a number.

I thought maybe starting with something like

if (Distance != double) 
    System.out.print ("You did not enter a valid character, please enter again." 

but that does not work. Any suggestions?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 4
    i think you need to turn back to Java 101. I'm not sure if Distance should be a class or an object.. also, you want `if (! Distance instanceof double` instead of `!=` – ddavison Sep 27 '13 at 19:58
  • Distance is a string, I am essentially learning Java 101 which is why I seem so novice. I appreciate the feedback though. – user2824855 Sep 27 '13 at 20:00
  • @user2824855. Why have you kept `distance` as String? Use `double` type instead. – Rohit Jain Sep 27 '13 at 20:02
  • That's totally ok! I'd refer to the answer by @RohitJain – ddavison Sep 27 '13 at 20:03

2 Answers2

2

You need to use Scanner#hasNextDouble() method to test, whether there is a double value to read:

// While the next input is not a double value, repeat
while (!keyboard.hasNextDouble()) {
    System.out.println("Please enter a valid numeric value");
    keyboard.nextLine();  // Move Scanner past the current line
}

double distance = keyboard.nextDouble();

Also, the loop might go infinite, if the user keeps on passing wrong input. You can give him some max number of attempt to get it right, and then throw some exception, or display some message, and then do a System.exit(1);.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • Thank you, that worked perfectly! I know it was a rookie mistake, I am trying to learn. Next time I will search harder, it is just difficult since I do not know all of the Java terms yet. Once again, thanks! – user2824855 Sep 27 '13 at 20:12
0

You can make this using a try cacth block, somethinh like:

System.out.print(" What is the distance in feet:" ); 
//ask the user to input variables 

Distance = keyboard.nextDouble(); 

try
{
  //you next code, considering a valid number 
}catch (NumberFormatException ex)
{
  //here u show a message ou another thing
}

Hope it helps ^^

Cold
  • 787
  • 8
  • 23