首页 > 解决方案 > Java 扫描器实用程序仅在我的简单程序中工作一次

问题描述

我是 Java 和一般编码的新手,我无法让第二个扫描仪来处理我的简单程序。在程序中使用第二个扫描仪会给我以下错误:

线程“main”中的异常你感觉如何?java.util.NoSuchElementException:找不到行

这是我的代码:

import java.util.Scanner;
public class Part2 {
public static void main(String[] args) {
    
    //This part asks the user how they are doing, and then it says hello to them
    Scanner userName = new Scanner(System.in);
    System.out.print("What is your name? ");
    String name = userName.nextLine();
    userName.close();
    System.out.println("Hello "+name);
    
    //This part asks the user how they are feeling, and then it says it is happy that they are feeling that way
    Scanner userAttitude = new Scanner(System.in);
    System.out.print("How are you feeling? ");
    String attitude = userAttitude.nextLine();
    userAttitude.close();
    System.out.println("Glad to hear you are feeling "+attitude);
    
    

}

}

标签: java

解决方案


不要关闭 System.in

当您关闭扫描仪时,它就是这样做的。

此外,无需在同一输入流上创建第二个 Scanner:使用第一个。


推荐阅读