2017-01-16 86 views
0

我只是java编码的初学者。java.lang.IllegalStateException:扫描程序关闭错误

这只是一个随机的程序,它处于代码的起始级别。

最近我得到这个错误,无法解决它。请帮我解决一下这个。

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) 

我的程序如下:

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

程序的日期部分工作完全正常。这个计划的第二部分是混乱的。

+1

您已关闭扫描仪在s.close();这就是为什么你不能使用它 – AMB

+0

你正在关闭扫描仪,然后使用它删除s.close() – 2017-01-16 10:24:58

+0

**真正**答案:去和谷歌你的异常消息**第一** – GhostCat

回答

0

您关闭扫描仪,然后调用nextInt

s.close(); //remove this line 

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

所以删除s.close();,你的代码将工作

+0

非常感谢。现在工作正常,但没有错误,但类钙计算操作无效。一旦我进入操作,我没有得到任何结果.. :( – Terminator

+0

@Terminator为什么你是这么想的吗?你永远不会打印结果! – Jens

+0

哦,是的,我忘记了nvm,非常感谢! – Terminator

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

删除声明

s.close(); 
0

不要关闭输入流,否则你将无法再读一遍。

s.close(); 

显示运算输出:

double d = c.compute(o); 
System.out.print("Result:" +d); 
+0

非常感谢。工作正常,没有错误,但运算compute()不能正常工作。 ( – Terminator

+0

)您是否收到任何异常?我认为它应该工作。将计算结果保存到某个变量并打印输出流。我正在编辑我的答案。祝你好运和快乐编码! – PyThon