Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input using scanner class in java

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

The error is--

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)

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.

Why this is happening...?

like image 960
Suyash Tilhari Avatar asked Dec 29 '15 10:12

Suyash Tilhari


1 Answers

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.

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

like image 97
Remi Avatar answered Sep 28 '22 05:09

Remi