Java 在 while 循环中尝试使用多个输入时出错

迪伦佩恩

以下 java 代码给出了以下错误:线程“main”中的异常 java.util.NoSuchElementException: No line found。

boolean running = true;
    while (running) {
        Scanner sc2 = new Scanner(System.in);
        System.out.println("Enter an item to order:");
        String name = sc2.nextLine();
        
        System.out.println("Enter the price:");
        String price = sc2.nextLine();
        
        System.out.println("Enter the quantity:");
        String quantity = sc2.nextLine();
        
        orderItems.add(name);
        orderItems.add(price);
        orderItems.add(quantity);
        orderItems.add(";");
        
        System.out.println("Would you like to add another item?: (y/n)");
        if (sc2.nextLine() != "y") {
            running = false;
        }
    }

有什么建议?我以前遇到过类似的错误,这是由于对每个输入使用新的扫描仪而不是对每个输入使用相同的扫描仪造成的,但此错误似乎是由不同的问题引起的。提前致谢。

阿西什·米什拉
  1. 仅声明一次您的扫描仪对象。您的 while 循环正在创建多个扫描仪(请参阅多个扫描仪对象

  2. 您没有以正确的方式执行字符串比较(请参阅如何在 Java 中比较字符串?

    boolean running = true;
    Scanner sc2 = new Scanner(System.in);
    while (running) {
        System.out.println("Enter an item to order:");
        String name = sc2.nextLine();
    
        System.out.println("Enter the price:");
        String price = sc2.nextLine();
    
        System.out.println("Enter the quantity:");
        String quantity = sc2.nextLine();
    
        orderItems.add(name);
        orderItems.add(price);
        orderItems.add(quantity);
        orderItems.add(";");
    
        System.out.println("Would you like to add another item?: (y/n)");
        if (sc2.nextLine().equals("y")) {
            running = false;
        }
    }
    

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章