异常在线程“主”java.util.NoSuchElementException无法找到我的情况的解决方案
问题描述:
我已经看过每个人在哪里合理的解释,我怎样才能解决这个问题。有人可以看我的代码,并给我一些建议。异常在线程“主”java.util.NoSuchElementException无法找到我的情况的解决方案
这里是我的代码:
import java.util.Scanner;
public class ShoppingCartManager {
public static void printMenu(ShoppingCart cart){
Scanner read = new Scanner(System.in);
String input = " ";
/* String itemName = "none";
String itemDescription = "none";
int itemPrice = 0;
int itemQuantity = 0;*/
System.out.println("MENU");
System.out.println("a - Add item to cart");
System.out.println("d - Remove item from cart");
System.out.println("c - Change item quantity");
System.out.println("i - Output items' descriptions");
System.out.println("o - Output shopping cart");
System.out.println("q - Quit");
//ItemToPurchase shopCart = new ItemToPurchase();
input = read.next();
read.close();
switch (input){
case "q" : System.out.println("Quit");
break;
}
}
public static void main(String[] args){
Scanner read = new Scanner(System.in);
String customerName = "none";
String todaysDate = "none";
System.out.println("Enter the Customer's name: ");
customerName = read.nextLine();
System.out.println("Enter Today's Date: ");
todaysDate = read.nextLine();
ShoppingCart cart = new ShoppingCart(customerName, todaysDate);
System.out.println("Customer Name: " + cart.getCustomerName());
System.out.println("Today's Date: " + cart.getDate());
read.close();
printMenu(cart);
return;
}
}
我得到的错误:在线程 “主要” java.util.NoSuchElementException
异常
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at ShoppingCartManager.printMenu(ShoppingCartManager.java:24)
at ShoppingCartManager.main(ShoppingCartManager.java:54)
答
你的问题是在调用read.close()
您的main
方法。这不仅关闭了扫描仪,还关闭了System.in
流。意思是说,无论何时您需要它(例如在您的printMenu
方法中),它都不可用。
在你的情况下,close()
调用是不必要的,你可以安全地删除它。
谢谢你的诀窍。现在我正在尝试使用switch语句创建菜单,并且在执行选项后,我试图让菜单在执行后再次打印,因此我已将printMenu方法分配给该选项以查看它是否会执行菜单再次,现在它给了我相同的异常错误。 – Sam
如果这为你工作,请不要忘记upvote并接受这个答案。 –
我做过了,但是因为我从昨天起才成为会员,所以不会反映投票。非常感激你的帮助。 – Sam