在java中使用scanner类输入

Suy*_*ari 5 java java.util.scanner

我正在制作一个程序,将给定的整数减少到最简单的比例.但是在程序的子方法中通过Scanner类获取输入时发生错误.这是代码:

package CodeMania;

import java.util.Scanner;

public class Question5 
{
public static void main(String args[])
{
    Scanner sc=new Scanner(System.in);
    int T=sc.nextInt();// number of test cases
    sc.close();
    if(T<1)
    {
        System.out.println("Out of range");
        System.exit(0);
    }
    for(int i=0;i<T;i++)
    {
    ratio();//line 19
    }

}
static void ratio()
{
    Scanner sc1=new Scanner(System.in);
    int N=sc1.nextInt();//line 26
    if((N>500)||(N<1))
    {
        System.out.println("Out of range");
        System.exit(0);
    }
    int a[]=new int[N];
    for(int i=0;i<N;i++)
    {
        a[i]=sc1.nextInt();
    }
    int result = a[0];
   for(int i = 1; i < a.length; i++)
        {
    result = gcd(result, a[i]);
    }
    for(int i=0;i<N;i++)
    {
        System.out.print((a[i]/result)+" ");
    }
    sc1.close();
}
static int gcd(int a, int b)
{
    while (b > 0)
    {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}
}
Run Code Online (Sandbox Code Playgroud)

错误是 -

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at CodeMania.Question5.ratio(Question5.java:26)
    at CodeMania.Question5.main(Question5.java:19)
Run Code Online (Sandbox Code Playgroud)

这里我在主函数中使用了2个单独的扫描仪对象sc,在比率函数中使用了sc1来从控制台获取输入.但是,如果我声明在类范围的公开静态型扫描仪的对象,然后使用整个程序只有一个扫描对象采取输入,则程序工作的要求没有错误.

为什么会发生这种情况......?

小智 5

出现此错误的原因是在扫描程序上调用.close()也会关闭inputStream System.in,但实例化新的Scanner不会重新打开它.

您需要在方法参数中传递单个扫描程序,或使其成为静态全局变量.