简体   繁体   中英

Java Scanner keep asking for input until variable is a double or int, or empty, at which point is given default value

here is the pseudo for what im asking

1. Take value
2. is value double or int?
3. if so, continue in program
4. else
5. is value empty?
6. if value empty; value=0.08
7. else
8. at this stage, value is not an empty valid, or a valid double or valid int
9. user did it wrong, prompt error
10. jump to step one take value

So to me this is pretty complicated, im new to this.

Ive been trying to impliment it like so;

while ( costscan.hasNext() )
  {
    double costperkm = costscan.nextDouble();
    if (costperkm=double){
      System.out.println("Value is double");
      System.out.println("FUEL COST SAVED ");
    }
    else {
            if(costperkm=null){
               costperkm=0.08;
          }
            else{

                }
    System.out.println("FUEL COST SAVED ");
         }
    System.out.print("\n");
    System.out.print("\n");
  }

My code above is the result of just playing about so at this stage it may not even make sense anymore. Hope someone can help, thanks.

The problem with hasNextDouble and nextDouble is that as long as the user just presses enter, they will both keep asking for input.

If you want to use a default value when the user simply presses enter, you should rather use Scanner.nextLine combined with Double.parseDouble , since nextLine is the only next-method that accepts empty input.

Here's a possible solution:

String input;
while(true) {
    input = costscan.nextLine();
    if(input.isEmpty()) {
        input = "0.08";
        break;
    }
    if(isParseable(input)) {
        break;
    }
    System.out.println("ENTER ONLY NUMBERS [DEFAULT 0.08]");
}
double costperkm = Double.parseDouble(input);

The method isParseable looks like this:

private static boolean isParseable(String str) {
    try {
        Double.parseDouble(str);
        return true;
    } catch(NumberFormatException e) {
        return false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM