Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Making a program "robust"

807601Feb 27 2008 — edited Feb 27 2008
So my initial problem was how to prevent any program I wrote from crashing if I asked the user for an integer, and they entered a double or a string.

Using Keyboard.hasNext() and Keyboard.next() I've been able to elude this problem. But now, if the user inputs two strings, that is: "box cover" or "daffy duck," my prompt asking for input will appear twice.

public static Scanner Keyboard=new Scanner(System.in);
public static double GetDoubleFromUser(){
     double value = -1;
     String invalidentry;
     while(value<0){
          System.out.print("Enter a double: ");
               if(Keyboard.hasNext()){
                    if(Keyboard.hasNextDouble()){
                         value=Keyboard.nextDouble;
                         return value;
                    }else {
                         invalidentry=Keyboard.next();
                    }
               }
         }
}
So the output would appear:

Enter a double: box box
Enter a double: Enter a double:

This has been bugging me for awhile, so any help would be greatly appreciated. I kind of understand the idea of Strings being broken into tokens, but I have no idea how to fix it.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 26 2008
Added on Feb 27 2008
5 comments
55 views