我正在设计一个简单的程序,用户输入项目#1名称的字符串值,然后输入项目#1价格的整数值,然后输入项目#1数量的整数值。当我编译程序然后运行它时,它允许我输入项目#1名称的用户输入,但不输入项目#2的名称。我不太清楚为什么这是因为它需要用户输入物品价格#2和物品数量#2。为什么会发生这种情况?
以下是两个相关的类文件:
ItemToPurchase.java:
public class ItemToPurchase {
private String itemName;
private int itemPrice;
private int itemQuantity;
public void defaultValues() {
itemName = "none";
itemPrice = 0;
itemQuantity = 0;
}
public void setName(String newName) {
itemName = newName;
}
public String getName() {
return itemName;
}
public void setPrice(int newPrice) {
itemPrice = newPrice;
}
public int getPrice() {
return itemPrice;
}
public void setQuantity(int newQuantity) {
itemQuantity = newQuantity;
}
public int getQuantity() {
return itemQuantity;
}
}
包含主类的类 -
ShoppingCartPrinter.java:
import java.util.Scanner;
public class ShoppingCartPrinter {
public static void main(String [] args) {
Scanner scnr = new Scanner(System.in);
ItemToPurchase item1 = new ItemToPurchase();
ItemToPurchase item2 = new ItemToPurchase();
System.out.println("Item 1");
System.out.println("Enter the item name:");
item1.setName(scnr.nextLine());
System.out.println(item1.getName());
System.out.println("Enter the item price:");
item1.setPrice(scnr.nextInt());
System.out.println(item1.getPrice());
System.out.println("Enter the item quantity:");
item1.setQuantity(scnr.nextInt());
System.out.println(item1.getQuantity());
System.out.println("");
System.out.println("Item 2");
System.out.println("Enter the item name:");
item2.setName(scnr.nextLine());
System.out.println(item2.getName());
System.out.println("Enter the item price:");
item2.setPrice(scnr.nextInt());
System.out.println(item2.getPrice());
System.out.println("Enter the item quantity:");
item2.setQuantity(scnr.nextInt());
System.out.println(item2.getQuantity());
scnr.close();
}
}
答案 0 :(得分:2)
这是因为Scanner#nextInt方法不消耗输入的最后一个换行符,因此在下一次调用Scanner#nextLine时会消耗换行符
解决方法:尝试将scnr.nextInt()
替换为Integer.parseInt(scnr.nextLine())