在这个程序中,我正在使用预设值从CarOrder类创建2个对象。然后,我要求用户另外两组值来创建另外两个对象。不幸的是,在输入第一个的税收状态后,它将跳过让用户在第二个上输入买方的值。为什么它会随机跳过这一个问题?
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
CarOrder speedy = new CarOrder("Speedy Rental", "Mini Cooper", 22150, 15, true);
CarOrder zip = new CarOrder("Zip Car Co.", "Ford Fusion", 27495, 6, true);
System.out.println("Enter Buyer: ");
String buyer1 = keyboard.nextLine();
System.out.println("Enter the type of car being purchased: ");
String car1 = keyboard.nextLine();
System.out.println("Enter the cost of this purchase: ");
double cost1 = keyboard.nextDouble();
System.out.println("Enter quantity of cars being purchased: ");
int quantity1 = keyboard.nextInt();
System.out.println("Enter tax status: ");
boolean tax1 = keyboard.nextBoolean();
System.out.println("Enter Buyer: ");
String buyer2 = keyboard.nextLine();
System.out.println("Enter the type of car being purchased: ");
String car2 = keyboard.nextLine();
System.out.println("Enter the cost of this purchase: ");
int cost2 = keyboard.nextInt();
System.out.println("Enter quantity of cars being purchased: ");
int quantity2 = keyboard.nextInt();
System.out.println("Enter tax status: ");
boolean tax2 = keyboard.nextBoolean();
CarOrder state = new CarOrder(buyer1, car1, cost1, quantity1, tax1);
CarOrder it = new CarOrder(buyer1, car2, cost2, quantity2, tax2);
System.out.println("Chicago Car Wholesalers" );
System.out.println("Oct. 30th, 2012");
System.out.println("New Car Order Report");
}
}
答案 0 :(得分:3)
keyboard.nextBoolean()
只读取布尔值。现在当你继续阅读keyboard.nextLine()
时,你会得到 Enter 键(这就是你正在谈论的跳过部分)。
在要求第二位买家后,您需要添加keyboard.nextLine();
。
答案 1 :(得分:3)
我认为nextBoolean()
正在消耗布尔值,但是留下行尾字符,然后您的nextLine()
将作为其输入消耗。因此,在要求第二个买家之前添加keyboard.nextLine()
。
答案 2 :(得分:1)
也许它没有跳过它,你在创建“它”时使用了错误的买家。仔细看看:
CarOrder state = new CarOrder(buyer1, car1, cost1, quantity1, tax1);
CarOrder it = new CarOrder(buyer1, car2, cost2, quantity2, tax2); // <-- This should be buyer2