简体   繁体   English

在这个由扫描器类和Java编写的简单计算器程序中,使用字符串中止“中止” while循环

[英]Abort with a string “abort” a while-loop in this simple calculator program made with scanner class and Java

Please help me to abort the while loop with sc.equals("abort") input/n at any time in the process. 请帮助我在过程中的任何时候使用sc.equals("abort") input / n中止while循环。

  public class Calculator {
        public static void main(String[] args) {
            double wert1, wert2, ergebnis;
            Scanner sc = new Scanner(System.in);
            boolean start = true;
            while(start) {
                try {
                    System.out.println("Pleaser Enter First Number");
                    wert1 = sc.nextDouble();

                    System.out.println("please Enter a Operator +,-,/,*");
                    String operator = sc.next();

                    System.out.println("please Enter second Value");
                    wert2 = sc.nextDouble();

                    if (operator.equals("+")) {
                        ergebnis = wert1 + wert2;
                        System.out.println("Das Ergebnis ist " + ergebnis);
                    }
                    if (operator.equals("-")) {
                        ergebnis = wert1 - wert2;
                        System.out.println("Das Ergebnis ist " + ergebnis);
                    }
                    if (operator.equals("*")) {
                        ergebnis = wert1 * wert2;
                        System.out.println("Das Ergebnis ist " + ergebnis);
                    }
                    if (operator.equals("/")) {
                        ergebnis = wert1 / wert2;
                        System.out.println("Das Ergebnis ist " + ergebnis);
                    }
                    if (sc.equals("abort")) {//why doesnt this work?
                        start = false;
                        break;
                    }
                } catch (InputMismatchException e) {

                    if (sc.equals("abort")) {//why doesnt this work?
                        start = false;
                        break;
                    }
                    else{sc.nextLine();}
                }
            }
        }
    }

Abort with a string "abort" a while-loop in this simple calculator program made with scanner class and Java. 在使用扫描器类和Java编写的简单计算器程序中,使用字符串“中止” while循环。

sc is the Scanner object, it does not represent directly what you type. scScanner对象,它不直接代表您键入的内容。 You can retrieve what you type with sc.next() . 您可以使用sc.next()检索您键入的内容。 You already defined String operator = sc.next() , so just use if (operator.equals("abort")) instead of if (sc.equals("abort")) . 您已经定义了String operator = sc.next() ,因此只需使用if (operator.equals("abort"))而不是if (sc.equals("abort"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM