扫描仪调试

时间:2016-02-13 13:47:59

标签: java

我在使用Scanner时遇到了一些问题 这是有问题的代码:

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

1 个答案:

答案 0 :(得分:1)

使用Scanner时,您应该只创建1并且不要关闭它们直到程序完成。这是因为关闭扫描程序会关闭传入的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 ");
}