I'm doing a simple Java calculator for school which works just fine. However, I need to add a while loop that asks the user if they want to continue yes/no. I can't figure out where I'm supposed to put the while statement though. I've tried putting above the if statement, I've tried below it and adding it into each if and else if statement and still can't get it to work. Where are you supposed to put a while loop within a if and else if statement to get all choices to run the while loop?
while (input.toUpperCase().equals("y"))
System.out.println("Do you want to continue? (y/n)");
input = calc.nextLine();
import java.util.Scanner;
public class loops {
public static void main(String[] args) {
Scanner calc = new Scanner (System.in);
double firstNum, secondNum, answer;
String input = "";
System.out.println("what would you like to do");
System.out.println("a. Add two numbers. ");
System.out.println("b. Subtract two numbers. ");
System.out.println("c. Multiply two numbers. ");
System.out.println("d. Divide two numbers. ");
System.out.println("Select a letter");
input.calc.nextLine();
if (input.equals("a")) {
System.out.println("Please enter your first number: ");
firstNum = calc.nextDouble();
System.out.println("Enter your second number: ");
secondNum = calc.nextDouble();
answer = firstNum + secondNum;
System.out.println("your answer is: " + String.valueOf (answer));
else if (input.equals("b")) {
System.out.println("Please enter your first number: ");
firstNum = calc.nextDouble();
System.out.println("Enter your second number: ");
secondNum = calc.nextDouble();
answer = firstNum - secondNum;
System.out.println("your answer is: " + String.valueOf (answer));
}
}
}
}
elseblock as well.do-whilestatement. put your calculation functionality inside of do block which makes it executes at least one time, and then checks continue or not in your while expressioninput.toUpperCase().equals("y")This condition will never equal true. You're converting the user input to upper case then checkingyas lower case.if-statementwithin yourwhileloop, aboveSystem.out.print("Do you want to continue? (y/n)");And fix yourwhileloop condition as Rick correctly pointed out.