Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 扫描仪调试_Java - Fatal编程技术网

Java 扫描仪调试

Java 扫描仪调试,java,Java,我在使用扫描仪时遇到一些问题 这就是问题代码: public static void main(String[] args) { System.out.println("Chose 1 or 2 = "); Scanner scan = new Scanner(System.in); byte a = scan.nextByte(); scan.close(); if (a==1) HW(); els

我在使用
扫描仪时遇到一些问题
这就是问题代码:

public static void main(String[] args) {
        System.out.println("Chose 1 or 2 = ");
        Scanner scan = new Scanner(System.in);
        byte a = scan.nextByte();
        scan.close();
        if (a==1) HW();
        else if (a==2) {
            System.out.print("Calculation program ... !\nInput Number 1st number = ");
            Scanner Catch = new Scanner(System.in);
            int x = Catch.nextInt();
            System.out.println("");
            System.out.print("Input Operand +,-,*,/ = ");
            Scanner Catchc = new Scanner (System.in);
            char z = Catchc.next().charAt(0);
            System.out.println("");
            System.out.print("Input 2nd number = ");
            Scanner Catch2 = new Scanner (System.in);
            int y = Catch2.nextInt();
            Catch.close();
            Catchc.close();
            Catch2.close();
        calc(x,y,z);
        }
        else System.out.println("Please input number 1 or 2 ");
    }
}
这是一个简单的计算器,我没有得到任何错误,程序没有终止,而是进行调试。它显示“无此类元素异常”

计算方法:

public static void calc(int x, int y, char z) {
  int result;
  result = 0;
  switch (z) {
   case '+': result = x + y;
   case '-': result = x - y;
   case '/': result = x / y;
   case '*': result = x * y;
  }
  System.out.println("Result of " + x + " " + z + " " + y + " is..." + " " + result);
 }

使用
Scanner
s时,您应该只创建1个,并且在程序完成之前不要关闭它们。这是因为关闭扫描仪会关闭传入的
InputStream
,而此InputStream是您程序的输入,因此您的程序在该点之后不会再接收输入

重写代码以仅创建1个扫描仪,并将其传递给其他函数:

public static void main(String[] args) { // TODO Auto-generated method stub
    System.out.println("Chose 1 or 2 = ");
    Scanner scan = new Scanner(System.in);
    byte a = scan.nextByte();
    if (a==1) 
        HW();
    else if (a==2) {
        System.out.print("Calculation program ... !\nInput Number 1st number = ");
        int x = scan.nextInt();
        System.out.println("");
        System.out.print("Input Operand +,-,*,/ = ");
        char z = scan.next().charAt(0);
        System.out.println("");
        System.out.print("Input 2nd number = ");
        int y = scan.nextInt();
        calc(x,y,z);
    }
    else 
        System.out.println("Please input number 1 or 2 ");
}

这很有帮助,谢谢@Ferrybig