Search code examples
javajava.util.scannerillegalstateexception

java.lang.IllegalStateException: Scanner closed ERROR


I'm just a beginner in java coding.

This is just a random program which is at a starting level of code.

Recently i got this error and was unable to solve it. Please help me with this.

Exception in thread "main" Enter the first number:java.lang.IllegalStateException: Scanner closed
    at java.util.Scanner.ensureOpen(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at New.main(New.java:19)

MY PROGRAM IS AS FOLLOWS:

import java.util.*;
public class New {
    public static void main(String args[]){
        int hour,min,sec,o;
        Scanner s = new Scanner(System.in);
        System.out.println("Enter the time:");
        hour=s.nextInt();
        min=s.nextInt();
        sec=s.nextInt();

        date  d = new date();
        d.setdate(hour,min,sec);
        System.out.println(d.display());
        s.close();

        calc c = new calc();
        int a,b;
        System.out.print("Enter the first number:");
        a=s.nextInt();
        System.out.print("Enter the second number:");
        b=s.nextInt();
        c.get(a,b);
        System.out.println("Which operation do you want to perform");
        System.out.println("1.Addition\n 2.Subtraction\n 3.Multiplication\n 4.Division");
        System.out.print("Enter the Operation:");
        o=s.nextInt();
        c.compute(o);

    }

    public class date {
    int hour,min,sec;

    public void setdate(int h,int m,int s){
        hour= ((h>0 && h<24)?h:0);
        min= ((m>0 && m<60)?m:0);
        sec= ((s>0 && s<60)?s:0);
    }
    public String display(){
        return String.format("%02d:%02d:%02d",hour,min,sec);
    }}



}
public class calc {
    int a,b,o;
    double c;
    public void get(int x,int y){
        a=x;
        b=y;
    }
    public double compute(int z){
        o=z;
    switch(o)
    {
    case 1: c=a+b;
    break;
    case 2: c=a-b;
    break;
    case 3: c=a*b;
    break;
    case 4: c=a/b;
    break;
    default: System.out.println("Invalid Operation");
    }
    return c;
    }
}

The date part of the program works perfectly fine. The mess is with the second part of the program.


Solution

  • You close the scanner and then call nextInt on it

     s.close(); //remove this line
    
     calc c = new calc();
        int a,b;
        System.out.print("Enter the first number:");
        a=s.nextInt();
    

    So remove s.close(); and your code will work