Java输入无法换行及InputMismatchException异常求助
问题说明
程序无法切换到下一行输入,针对商品1和商品2尝试过next()和nextLine()方法均出现相同错误。程序需要接收可能包含1个或2个单词的商品名称,当前使用的输入格式为教授要求,且教授明确要求商品2的输入必须使用nextLine()。另外教授已群发邮件告知使用的输入格式存在问题,在问题修复前暂不清楚是否存在实际问题。
代码实现
import java.util.Scanner; public class ShoppingCartPrinter { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); int i = 0; String productName = ""; int productPrice = 0; int productQuantity = 0; int cartTotal = 0; ItemToPurchase item1 = new ItemToPurchase(); ItemToPurchase item2 = new ItemToPurchase(); //get item 1 details System.out.println("Item 1"); System.out.println("Enter the item name: "); item1.setItemName(scnr.nextLine()); //get and set item 1 name System.out.println("Enter the item price: "); item1.setItemPrice(scnr.nextInt()); //get and set item 1 price System.out.println("Enter the item quantity: "); item1.setItemQuantity(scnr.nextInt()); //get and set item 1 quantity scnr.nextLine(); //consume next line (i've tried with and without this part as well) System.out.println("Item 2"); System.out.println("Enter the item name: "); item2.setItemName(scnr.nextLine()); //get and set item 2 name System.out.println("Enter the item price: "); item2.setItemPrice(scnr.nextInt()); //get and set item 2 price System.out.println("Enter the item quantity: "); item2.setItemQuantity(scnr.nextInt()); //get and set item 2 quantity System.out.println(); System.out.println("TOTAL COST"); System.out.println(item1.getItemName() + " @ $" + item1.getItemPrice() + " = " + (item1.getItemPrice() * item1.getItemQuantity())); System.out.print("Total: " + (item1.getItemPrice() + item2.getItemPrice())); // Add costs of two items and print total // cartTotal = item one price + item two price // Totoal Cost // item one information // item two information // Total output return; } }
报错信息
Exception in thread "main" java.util.InputMismatchException at java.base/java.util.Scanner.throwFor(Scanner.java:939) at java.base/java.util.Scanner.next(Scanner.java:1594) at java.base/java.util.Scanner.nextInt(Scanner.java:2258) at java.base/java.util.Scanner.nextInt(Scanner.java:2212) at ShoppingCartPrinter.main(ShoppingCartPrinter.java:21)
要求的输入格式(zY Books IDE中必须按此输入)
canned pears 5 1 fresh apples 2 1
程序运行表现
程序运行时输出如下,输入价格5后终止:
Item 1
Enter the item name: canned pears
Enter the item price: 5 //此处程序终止
内容的提问来源于stack exchange,提问作者Ashley Brown
相关产品推荐
相关产品推荐

