当我Scanner在 java 中获取字符时,编译器抛出:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at ShoppingCartManager.getChar(ShoppingCartManager.java:37)
at ShoppingCartManager.printMenu(ShoppingCartManager.java:56)
at ShoppingCartManager.main(ShoppingCartManager.java:30)
这是抛出异常的代码部分
private static final Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
System.out.println("Enter Customer's Name:");
String name = scnr.nextLine();
System.out.println("Enter Today's Date:");
String date = scnr.nextLine();
System.out.println();
ShoppingCart cart = new ShoppingCart(name, date);
System.out.println("Customer Name: " + name);
System.out.println("Today's Date: " + date + "\n");
printMenu(cart);
scan.close();
}
private static char getChar () {
char option;
while (true) {
try {
option = scan.next().charAt(0);
break;
} catch (Exception exc) {
continue;
}
}
return option;
}
public static void printMenu(ShoppingCart cart) {
while(true) {
System.out.println("MENU");
System.out.println("g - Add Guitar to cart");
System.out.println("c - Add Candy Bar to cart");
System.out.println("s - Add Shoes to cart");
System.out.println("d - Remove item from cart");
System.out.println("n - Change item quantity");
System.out.println("i - Output items' descriptions");
System.out.println("o - Output shopping cart");
System.out.println("q - Quit" + "\n");
System.out.println("Choose an option:");
char option = getChar();
if (option == 'q') {
return;
}
我该怎么办?
潇湘沐
青春有我
相关分类