我在使用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);
 }

最佳答案

使用Scanner时,应仅创建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 ");
}

关于java - 扫描仪调试,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35380717/

10-10 16:54