使用继承和扫描仪进行简单计算我如何处理这些异常?

Simple calculate using inheritance and Scanner how i handle these Exceptions?

我也在尝试使用扫描仪和继承制作一个简单的计算器,在我插入两个数字和运算符后我发现了这个异常

例外是:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextShort(Scanner.java:1987)
at java.util.Scanner.nextShort(Scanner.java:1946)
at calculator.simplecalc.<init>(simplecalc.java:18)
at calculator.simplecalc_inhe.<init>(simplecalc_inhe.java:7)
at calculator.Calculator.main(Calculator.java:6)

我的 Java 代码:第一个 class 是 Superclass 它的名字是 simplecalc.java

 package calculator;
 import java.util.Scanner;

 public class simplecalc {

    private int val1;
    private int val2;
    private Scanner sca;
    public char op;
    public int result;

    public simplecalc () 
    {
        sca = new Scanner(System.in);
        System.out.println("Enter the first number");
        val1 = sca.nextInt();
        System.out.println("Enter the Second number");
        val2 = sca.nextInt();
        System.out.println("choose an operator + or - or * or / ");
        op = (char) sca.nextShort();
        System.out.println(op);
    }

    /*use if operator not equal + or - */
    public char set_op()
    {
        op = (char) sca.nextShort();
        return op;
    }


    public int calsum()
    {
        return this.val1 + this.val2; 
    }

    public int calsub()
    {
        return this.val1 - this.val2; 
    }

    //i don't use setX and setX i write them because i use getX,Y

    /* public void setX(int x)
    {
        this.val1 = x;
    }
    public void setY(int y)
    {
        this.val2 = y;
    } */

    public int getX()
    {
        return this.val1;
    }
    public int getY()
    {
        return this.val2;
    }

}

子class: simplecalc_inhe.java

package calculator;

public class simplecalc_inhe extends simplecalc {

    public simplecalc_inhe()
    {
        super();
    }


    public int mult()
    {
        return this.getX() * this.getY();
    }

     public int div()
    {
        int z = this.getY();
        if(z == 0){
            return 0;
        }
        return this.getX() / z;
    }
}

主要-class: Calculator.java

package calculator;

public class Calculator {

    public static void main(String[] args) {
        simplecalc_inhe cal = new simplecalc_inhe();

        if (cal.op != '+' || cal.op != '-' || cal.op != '*' || cal.op != '/' )
        {
            System.out.println("You must enter a vaild operator");
            cal.set_op(); //to set operator 

        } else {

            if(cal.op == '+' ) {
                cal.result = cal.calsum();
                System.out.println(cal.result);

            }else if(cal.op == '-') {
                cal.result = cal.calsub();
                System.out.println(cal.result);

            }else if(cal.op == '*') {
                cal.result = cal.mult();
                System.out.println(cal.result);

            }else if(cal.op == '/') {
                cal.result = cal.div();
                System.out.println(cal.result);
            }
        }
    }
}

我希望我用大部分细节很好地解释了那个错误,谢谢。

From the Java doc itself :

public short nextShort() : Scans the next token of the input as a short.

Throws:

InputMismatchException - if the next token does not match the Integer regular expression, or is out of range

因为 +/-* 不匹配 Integer

Ypu 可以使用 op = sca.nextLine().charAt(0);


此外,要正确使用 return 行,最好这样做:

val1 = Integer.parseInt(sca.nextLine());
val2 = Integer.parseInt(sca.nextLine());
op = sca.nextLine().charAt(0);

还有你的测试如果不好,因为如果你输入一个'-',它会和'+'不同 所以真的你会og到if,事实上你需要og inot 如果它不同于所有 4 种可能,请按 :

修复
if (cal.op != '+' && cal.op != '-' && cal.op != '*' && cal.op != '/' )
    

询问用户,直到他给出一个好的操作员,你可以这样做:(但它也会再次询问 2 个整数,因为它是相同的方法)/为了避免相同的代码,最好把 print最后,使用一个开关,它的性能更高:

do{
   System.out.println("You must enter a vaild operator");
   cal.set_op(); //to set operator 
} while(cal.op != '+' && cal.op != '-' && cal.op != '*' && cal.op != '/' );

switch(cal.op){
       case '+':
          cal.result = cal.calsum();
          break;
       case '-':
          cal.result = cal.calsub();
          break;
       case '*':
          cal.result = cal.mult();
          break;
       case '/':
          cal.result = cal.div();
          break;
      default : break;     //safety check
}
System.out.println(cal.result);   //try to not have SAME code written twice (or more^^)


        

你的问题是:

    System.out.println("choose an operator + or - or * or / ");
    op = (char) sca.nextShort();

+ 和 - 和 * 和 / 都不能读成 nextShort

您可以使用

public String next(Pattern pattern)

Returns the next token if it matches the specified pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext(Pattern) returned true. If the match is successful, the scanner advances past the input that matched the pattern.

link

首先,扫描器旨在检索由白色 space 字符分隔的值行。所以如果你想读一个字符然后使用

op = (char)System.in.read()

上面这行将获取您输入的字符,这样您就不必担心 IndexOutofBoundException,因为您没有从索引中获取,也没有 NullPointerException,因为您使用的是变量而不是对象。
所以现在看看你的代码很明显你正在编写一个接受字符并执行操作的方法所以在这种情况下你可以简单地创建一个开关案例并按案例检查所有可能的操作并从默认案例中抛出错误消息

因此将您的代码重构为

public void doOperation() {
 switch(cal.op)
{
    case '+' : 
        cal.result = cal.calsum();
        System.out.println(cal.result);
        break;

    case  '-' :
        cal.result = cal.calsub();
        System.out.println(cal.result);
        break;

    case  '*' :
          cal.result = cal.mult();
          System.out.println(cal.result);
          break;
    case '/' :
        cal.result = cal.div();
        System.out.println(cal.result);
        break;
    default : System.out.println("You must enter a vaild operator");
           cal.set_op();
           doOperation(); 
       }
   }