2

In this program, I'm creating 2 objects from the CarOrder class with preset values. I'm then asking the user for another 2 sets of values to create 2 more objects. Unfortunately, after entering tax status for the first one, it will skip letting the user enter a value for the buyer on the second one. Why is it randomly skipping this one question?

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");

}

}

4

3 回答 3

3

我认为nextBoolean()正在消耗布尔值但留下行尾字符,然后您nextLine()将其用作输入。因此,keyboard.nextLine()在要求第二个买家之前添加。

于 2013-03-05T19:04:23.247 回答
3

keyboard.nextBoolean()只读取布尔值。现在,当您继续阅读时,keyboard.nextLine()您将获得Enter关键(这就是您正在谈论的跳过部分)。

您需要keyboard.nextLine();在询问第二个买家后添加。

于 2013-03-05T19:03:15.823 回答
1

也许它没有跳过它,你在创建“它”时使用了错误的买家。仔细看看这个:

CarOrder state = new CarOrder(buyer1, car1, cost1, quantity1, tax1);
CarOrder it = new CarOrder(buyer1, car2, cost2, quantity2, tax2); // <-- This should be buyer2
于 2013-03-05T19:02:23.780 回答