如何输入双变量?

时间:2016-09-30 22:04:59

标签: java

当我运行此代码并输入第一个变量的double值时,即 在线程“main”java.util.InputMismatchException中,它在read.nextDouble()行上显示错误为异常。

/**
 * Created by Ranjan Yadav on 1.10.2016.
 */
public class GasMileage {
    public static void main(String[] args){
        java.util.Scanner read = new java.util.Scanner(System.in);
        int counter = 0;
        System.out.println("Miles Driven(press 1 to quit): ");
        double miles = read.nextDouble();
        double totalGalon = 0;
        double totalMiles = 0;
        double milesPerGalon = 0;
        double totalMilesPerGalon = 0;
        totalMiles += miles;
        while(miles != 1){
            System.out.println("Gallon used: ");
            double galon = read.nextDouble();
            counter++;
            milesPerGalon = miles / galon;
            totalMilesPerGalon += milesPerGalon;
            System.out.println("Miles per gallon: " + milesPerGalon);
            System.out.println("Miles Driven(press 1 to quit); ");
            miles = read.nextDouble();
            totalGalon += galon;
            totalMiles += miles;
        }
        if(counter == 0 ){
            System.out.println("No values were entered.\nThanks for Using!\n\n");
        }else{
            double avg = totalMilesPerGalon / counter;
            System.out.printf("Total miles driven: %.2f" , totalMiles);
            System.out.printf("Total gallons used: %.2f" , totalGalon);
            System.out.printf("Miles per gallon for all trips: %.2f" , totalMilesPerGalon);
        }
    }
}

1 个答案:

答案 0 :(得分:-1)

来自Javadoc

  

抛出:

     
      
  • InputMismatchException - 如果下一个标记与Float正则表达式不匹配,或者超出范围
  •   

基本上,你输入的不是数字。