0

Below is my code for a "Do-While" loop. I can't figure out why it's terminating before I even get to enter in the value for my variable "redo" at the end of the do {} section. It terminates right after printing the "would you like to do this again" part.

import java.util.Scanner;
public class AlgWorkbench0402 {

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

        String redo;

        do {
            System.out.println("Enter in two integers and get the sum.");
            int val1, val2;
            val1 = Integer.valueOf(scanner.nextInt());
            val2 = Integer.valueOf(scanner.nextInt());

            System.out.println(val1 + val2);
            System.out.println("Would you like to do this again? [y/n]");

            redo = scanner.nextLine();

        }
        while (redo == "y" || redo == "Y");
    }
}
  • 2
    Use `next()` instead of `nextLine()`. Also don't compare strings using `==` since for non-primitive types (objects) `==` tests for reference equality (if references point to same object), not if two (even separate) objects are equal. To check for equality use `equals` method like `str1.equals(str2)` or when you don't care about case use `str1.equalsIgnoreCase(str2)`. – Pshemo Apr 06 '20 at 17:39
  • For more details about problems you are facing see duplicate targets above your question (you may need to refresh this page to see them). – Pshemo Apr 06 '20 at 17:43
  • @Pshemo thank you so much! thats exactly what I was looking for! –  Apr 06 '20 at 19:55

0 Answers0