0

在我的测试程序文件中,我试图从用户那里接收 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());
    }

}
4

1 回答 1

1

问题是您正在使用:

double inputAmount = in.nextDouble();

它不仅会读取您的第一个输入金额,还会将回车符传递给下一条readLine语句。

解决方法是先消耗回车:

double inputAmount = Double.parseDouble(in.nextLine());
于 2012-08-24T22:59:12.747 回答