为什么我一直收到nosuchelementexception错误?

时间:2016-10-02 14:32:08

标签: java input java.util.scanner

我是编程新手。我试图通过使用Scanner类从用户那里获得多个输入。我使用net bean并尝试在net beans IDE中运行和编译我的代码。只要我在请求输入后没有关闭扫描仪,程序就会运行并编译。但是当我每次请求输入后尝试关闭扫描仪时,我都会收到nosuchelementexception扫描仪关闭错误。在课堂上,我们被教导在每次请求用户输入后关闭扫描仪。我的教授也这样做,同时使用NetBeans并且他的程序每次编译和运行。像我一样,他也只声明一次扫描程序,并在要求用户输入时多次使用相同的变量。

    import java.util.Scanner; // This allows us to use Scanner

public class GettingInput {
public static void main(String[] args) {
// ALWAYS give the user instructions. System.out.println("Enter an integer: ");

    // Create a new scanner
    Scanner keysIn = new Scanner(System.in);
    // Specify the type of data/variable you are scanning in
    int num = keysIn.nextInt();
    // Close your scanner when you are done.
    keysIn.close();
    // ALWAYS confirm that you scanned in what you thought you did.
    System.out.println("Your int: " + num);

    // Repeat the process for a different data type
    System.out.println("---------");
    System.out.println("Enter a floating-point value:");
    keysIn = new Scanner(System.in);
    double num2 = keysIn.nextDouble(); // note the different method
    keysIn.close();
    System.out.println("Your floating-point: " + num2);

    // Repeat it yet again
    System.out.println("---------");
    System.out.println("Now enter a string.");
    keysIn = new Scanner(System.in);
    String str = keysIn.nextLine(); // again, a different method
    keysIn.close();
    System.out.println(str);       
 }
}

这是他在课堂上编写,编译和运行的代码。当我尝试运行相同的代码时,它不起作用。

我还使用Mac Book Pro和最新版本的Mac OS。

1 个答案:

答案 0 :(得分:0)

发生这种情况是因为您关闭了扫描仪并再次启动扫描仪对象。因此,最好不要关闭扫描仪,因为您知道以后会在代码中再次使用它,但是一旦完成它就应该这样做。

另一件事是,对于不同类型的输入,您甚至不需要再次创建整个扫描仪对象,您可以为相应的输入类型调用该扫描仪的适当方法。这样

import java.util.Scanner;

public class GettingInput {
    public static void main(String[] args) {
        Scanner keysIn = new Scanner(System.in);
        int num = keysIn.nextInt();
        System.out.println("Your int: " + num);

        System.out.println("---------");
        System.out.println("Enter a floating-point value:");
        double num2 = keysIn.nextDouble(); 
        System.out.println("Your floating-point: " + num2);

        System.out.println("---------");
        System.out.println("Now enter a string.");
        String str = keysIn.next(); 
        keysIn.close();
        System.out.println(str);
    }
}