使用两种方法在Java中获取多个用户输入

时间:2018-07-26 17:30:36

标签: java methods java.util.scanner

我正在研究一些基本的Java技能,当我在调试时得到了NoSuchElementExemption。我的目标是用两种不同的方法提出两个问题,并将其结合到主要功能中。有人可以解释我违反的规则吗?

代码如下:

import java.util.Scanner;

public class TwoInputs{

    public static double test()
    {
        Scanner reader2 = new Scanner(System.in);
        System.out.println("Enter a number ");

        double n2 = reader2.nextDouble();
        if (n2 %1 != 0) {
            System.out.println("Number is invalid");    
        } else {
            reader2.close(); 
            System.out.println("You put the number " + n2); 
        }
        return n2;
    }

    public static double test2()
    {
        Scanner reader1 = new Scanner(System.in);
        System.out.println("Enter a number ");

        double n1 = reader1.nextInt();
        if (n1 %1 != 0) {
            System.out.println("Number is invalid");
        } else {
            reader1.close(); 
            System.out.println("You put the number " + n1); 
        }
        return n1;
    }

    public static void main(String[] args) {
        double sum = test();
        double sum2 = test2();
        System.out.println("You put the number " + sum+ "and"+ sum2);   
    }
}

1 个答案:

答案 0 :(得分:0)

我认为通过关闭阅读器,输入流也将被关闭。即您无法使用System.in打开其他扫描仪。尝试这种方式:

import java.util.Scanner;

    public class Main {
public static double test(Scanner scanner)
{
    System.out.println("Enter a number ");

    double n2 = scanner.nextDouble();
    if (n2 %1 != 0) {
        System.out.println("Number is invalid");

    } else {
        System.out.println("You put the number " + n2);
    }
    return n2;
}

public static double test2(Scanner scanner)
{
    System.out.println("Enter a number ");
    double n1 = scanner.nextInt();
    if (n1 %1 != 0) {
        System.out.println("Number is invalid");

    } else {
        System.out.println("You put the number " + n1);
    }
    return n1;
}

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);
    double sum = test(scanner);
    double sum2 = test2(scanner);
    System.out.println("You put the number " + sum+ "and"+ sum2);

}
}