使用Java中的扫描器类输入 [英] Input using scanner class in java

查看:76
本文介绍了使用Java中的扫描器类输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was making a program to reduce given integers to their simplest ratio.But an error is occurring while taking inputs through Scanner class in a sub-method of program.Here is the code :

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;
}
}

错误是-

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)

在这里,我在主功能中使用了2个单独的扫描仪对象sc,在比率功能中使用了sc1从控制台获取输入. 但是,如果我在类范围内声明了一个公共静态类型的Scanner对象,然后在整个程序中仅使用一个Scanner对象作为输入,那么程序将按要求正常工作,而不会出现错误.

Here I have used 2 seperate scanner objects sc in main function and sc1 in ratio function to take input from console. However if I am declaring a public static type Scanner object in class scope and then using only one Scanner object throughout the program to take input then program is working as required without error.

为什么会这样...?

推荐答案

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

The reason for this error is that calling .close() on the scanner also closes the inputStream System.in, but instantiating a new Scanner will not re-open it.

您需要在方法参数中传递单个Scanner,或者将其设置为静态全局变量.

You need to either pass a single Scanner around in your method parameters, or make it a static global variable.

这篇关于使用Java中的扫描器类输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆