-1

電卓は、0 で除算するか、整数以外を使用すると終了します。while ループが機能しません。

誰でも助けて、この問題を解決する方法を説明できますか?

編集:

それでも終了します。

package b;

import java.util.*;


public class Calculator3{


    static boolean _state = true;
    public static void main (String[] args){

        System.out.println("Usage: operand1 operator operand2");
        System.out.println("Operands are integers");
        System.out.println("Operators: + - * /");

        Scanner in = new Scanner(System.in);

        do{


        int result = 0;
        int operand1 = 0;
        int operand2 = 0;
        String operator = " ";
        char op = ' ';

        try{
        operand1 = in.nextInt();
        operator = in.next();
        op = operator.charAt(0);
        operand2 = in.nextInt();}

        catch (InputMismatchException e){
            System.out.println("One or both of the operands are non-integers. Please check your operands");
            break;}





            try{
                switch (op){
                    case '+': result = operand1 + operand2;
                    break;
                    case '-': result = operand1 - operand2;
                    break;
                    case '*': result = operand1 * operand2;
                    break;
                    case '/': result = operand1 / operand2;
                    break;
                    default: System.out.println("Unknown Operator");
                    break;}

            }

            catch(RuntimeException e){
                System.out.println("Operand2 cannot be 0");
                System.exit(0);}


            finally{
                System.out.println("Answer: " + operand1 + ' ' + op + ' ' + operand2 + " = " + result);}
        }
            while (_state = true);}}
4

5 に答える 5

4
} while (_state = true);

する必要があります

} while (_state == true);

またはそれ以上

} while (_state);

ループを早期に終了しないようにするには、次の条件を回避する必要があります。

  • 値と演算子を間違った順序で入力する
  • ArithmeticExceptionなどの原因となる表現を使用し3/0ます。
于 2013-07-01T21:23:42.420 に答える
0

プログラムは 2 つの条件で終了します。最初は catch (InputMismatchException e){ System.out.println("One or both of the operands are non-integers. Please check your operands"); break;}

double や float などの非整数の場合でも続行したい場合は、このブレークを削除してください。

2番目は

` catch(RuntimeException e){
            System.out.println("Operand2 cannot be 0");
            System.exit(0);}`

System.exit(0) が原因でこの while ループが壊れています。続行する場合は、System.exit(0); を削除してください。

于 2013-07-01T21:47:31.370 に答える