在Java中使用DoWhile

时间:2014-12-09 21:39:06

标签: java eclipse

当我尝试使用字符串在Java中执行dowhile循环时,它只是终止程序而没有错误,如果我想继续,我没有机会进入。如果使用字符串请求,如何使程序循环?

public static void main(String args[]) {        
    Scanner user_input = new Scanner (System.in);
    Maths math = new Maths();

    double firstNum, secondNum;
    String calcAgain = null;

    do{


    System.out.println("Enter First Number: ");
    firstNum = user_input.nextDouble();
    System.out.println("Enter Second Number: ");
    secondNum = user_input.nextDouble();

    System.out.println("Please select an operation! (+,-,*,/)");

    String operation = user_input.next();

    if (operation.equals("+")) {
        System.out.println(math.add(firstNum, secondNum));
    }

    else if (operation.equals("-")) {
        System.out.println(math.subtract(firstNum, secondNum));
    }

    else if (operation.equals("*")) {
        System.out.println(math.multiply(firstNum, secondNum));
    }

    else if (operation.equals("/")) {
        System.out.println(math.divide(firstNum, secondNum));
    }

    else {
        System.out.println("Invalid Function!");
    }

    System.out.println("Would you like to do another calculation? ");

    calcAgain = user_input.nextLine();


}while(calcAgain == "yes");

1 个答案:

答案 0 :(得分:3)

您可能希望查看字符串操作是否相等。条件 while(calcAgain ==" yes")将永远不会执行,因为您正在比较对象本身。字符串相等是使用 .equals()函数完成的。