在我的测试文件中,我试图从用户接收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());
}
}
答案 0 :(得分:1)
问题在于你正在使用:
double inputAmount = in.nextDouble();
不仅会读取您的第一个输入金额,而且会将回车符传递给下一个readLine
语句。
解决方案是首先使用回车:
double inputAmount = Double.parseDouble(in.nextLine());