猿问

java.util.NoSuchElementException 的问题:找不到行

当我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;


        } 

我该怎么办?


慕仙森
浏览 617回答 2
2回答

潇湘沐

使用 Scanner 你需要检查下一行是否有 hasNext() 这样循环就变成了while(sc.hasNext()){str=sc.next().charAt(0);//...}

青春有我

使用扫描仪时还需要检查是否有下一行,可用于hasNextLine()执行此检查。
随时随地看视频慕课网APP

相关分类

Java
我要回答