-3

When I try to do a dowhile loop in Java with a string it just terminates the program without an error not giving me a chance to enter if I would like to continue. How do I make my program loop if requested using a string?

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");
NinjaCatz
  • 1
  • 2
  • Do `calcAgain.equals("yes")`. Check out [How do I compare Strings in Java](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Dioxin Dec 09 '14 at 21:40
  • 1
    You seem to use `equals` correctly in the rest of your program, why not in the while condition? – August Dec 09 '14 at 21:40
  • Please see [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) and [Skipping nextLine() after use nextInt()](http://stackoverflow.com/questions/13102045/skipping-nextline-after-use-nextint). – rgettman Dec 09 '14 at 21:41

1 Answers1

3

You might want to look at string operations for equality. The condition while(calcAgain == "yes") will not execute ever, because you are comparing the object itself. String equality is done with the .equals() function.

Jake Byman
  • 543
  • 12
  • 25