运行时错误-跳过一行用户输入(扫描仪)

7nbnzgx9  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(276)

在我的tester文件中,我试图从用户那里接收3个输入,但是只接收到2个输入,而且程序似乎跳过了in.nextline()代码行。这是我的密码:

import java.util.Scanner;

public class IngredientTester
{
   public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        /*These 3 inputs work */
        System.out.println("Please enter Ingredient name.");
        String inputName = in.nextLine();
        System.out.println("Please enter Ingredient measurement type.");
        String inputType = in.nextLine();
        System.out.println("Please enter Ingredient amount");
        double inputAmount = in.nextDouble();

        Ingredient inputIngredient = new Ingredient(inputName,inputType,inputAmount);
        System.out.println(inputIngredient.getName() + "- " + inputIngredient.getAmount() + " " + inputIngredient.getMeasurement());

        System.out.println("Please enter Ingredient name.");
        inputName = in.nextLine();
                /* ^ the input above does not work, but the ones below do work */
        System.out.println("Please enter Ingredient measurement type.");
        inputType = in.nextLine();
        System.out.println("Please enter Ingredient amount");
        inputAmount = in.nextDouble();

        inputIngredient.setAmount(inputAmount); 
        inputIngredient.setName(inputName); 
        inputIngredient.setMeasurement(inputType);
        System.out.println(inputIngredient.getName() + "- " + inputIngredient.getAmount() + " " + inputIngredient.getMeasurement());
    }

}
qcbq4gxm

qcbq4gxm1#

问题是您正在使用:

double inputAmount = in.nextDouble();

它不仅读取第一个输入量,而且将回车传递给下一个 readLine 声明。
解决方案是先使用回车符:

double inputAmount = Double.parseDouble(in.nextLine());

相关问题