I am writing a program for class for recursion. That part works perfectly. But I also need to repeat the program until the user chooses to quit.
My program prompts to repeat the program but doesn't wait for a response. Instead it quits right away.
I added a comment in the code below I believe where the problem lies.
import java.util.*;
public class Recursion{
public static int sumOfInt(int x)
{
int sum =0;
if (x <= 1)
return x;
else
sum += x % 10;
x /= 10;
return sum + sumOfInt(x);
}
public static void main (String [ ] arg){
Scanner sc = new Scanner(System.in);
int userInt = 0;
boolean userInput = false;
boolean endLoop = false;
String userAgain = "";
do{
do{
try{
System.out.print("Please enter an integer number: ");
userInt = sc.nextInt();
userInput = true;
}
catch(InputMismatchException ime) {
System.out.println("You did not enter an integer number");
sc.nextLine();
}
}while(userInput == false);
System.out.println("The integer you entered is " + userInt);
System.out.println("The sum of the digits in the integer you entered is " + sumOfInt(userInt));
System.out.println();
System.out.println("Enter yes to try again");
userAgain = sc.nextLine();
// I don't understand why the above line is not waiting for a user response before quitting.
if(userAgain == "yes"){
endLoop = false;
}else{
endLoop = true;
}
}while(endLoop == false);
}
}