自从我真正为 java 编写任何基于控制台的东西以来已经有一段时间了,
我有下面这个方法,它应该询问我每一行,对吧?相反,我收到一个提示,然后是三个提示。我在这里做错了什么?
try {
System.out.println("Please enter the product's LONG details: ");
product.setLongDetails(sc.next()); //set products long details
System.out.println("Please enter the product's SHORT details: ");
product.setShortDetails(sc.next()); //set short details
System.out.println("Please enter the product's UPC data: ");
product.setUpc(sc.next()); //set upc
System.out.println("Please enter the product's stock: ");
product.setStock(sc.nextInt());
System.out.println("Please enter the products price. ");
System.out.println("This MUST be entered with no dollar sign.");
product.setPrice(sc.nextBigDecimal());
InventoryManager.addProduct(product); //add product to database
}
我的控制台输出如下:
Please enter the product's LONG details:
Fireplace Cleaning Package
Please enter the product's SHORT details:
Please enter the product's UPC data:
Please enter the product's stock:
BUILD STOPPED (total time: 3 minutes 5 seconds)
扫描仪在类声明中初始化为:
public static Scanner sc = new Scanner(System.in); //class level scanner object for reuse.
如果我在每个对象设置方法之间调用 sc.nextLine(),它会正确提示但获取错误信息:
Please enter the product's SHORT details:
Fire Poker
将对象显示为:
请输入您的选择:
火
最佳答案
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
这意味着当您输入带有空格的文本(例如示例中的“壁炉清洁包”)时,它会分为 3 个不同的输入,每个输入均由 sc.next() 的一次调用返回
.
解决方案是将分隔符模式调整为换行符:
sc.useDelimeter("\\r?\\n");
关于Java扫描器对象跳行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35260699/