#GPT-4 Conversation #1103584687630323752
1 messages · Page 1 of 1 (latest)
How do I get this code to repeat itself after it asks "Would you like to repeat this program? (Y/N)"?
"import java.util.Scanner;
public class Review {
public static void main(String[] args) {
// declaration of variable
double firstNumber;
double secNumber;
double output;
double cont;
Scanner myObj = new Scanner(System.in);
do {
System.out.println("Enter first number");
// double input
firstNumber = myObj.nextDouble();
System.out.println("Enter second number");
// double input
secNumber = myObj.nextDouble();
output = (firstNumber + secNumber)/2;
System.out.println("Average of The Two Numbers: " + output);
System.out.println("Would you like to repeat this program? (Y/N)");
cont = myObj.nextDouble();
}
while (true);
}
}"
To repeat the code after asking "Would you like to repeat this program? (Y/N)", you need to use a boolean variable to track the user's input, and nextLine() function after nextDouble() to clear the buffer.
Here's your updated code:
import java.util.Scanner;
public class Review {
public static void main(String[] args) {
// declaration of variables
double firstNumber;
double secNumber;
double output;
String cont;
Scanner myObj = new Scanner(System.in);
do {
System.out.println("Enter first number");
// double input
firstNumber = myObj.nextDouble();
System.out.println("Enter second number");
// double input
secNumber = myObj.nextDouble();
output = (firstNumber + secNumber) / 2;
System.out.println("Average of The Two Numbers: " + output);
System.out.println("Would you like to repeat this program? (Y/N)");
myObj.nextLine(); // Clear the buffer
cont = myObj.nextLine().toUpperCase(); // Get user input
} while (cont.equals("Y"));
}
}
I changed the cont variable to a String and used nextLine() to properly handle the user's input. The loop will only continue if the user enters "Y" or "y".
@plush sapphire Can you make it so "while" is true
Hi! You don't need to mention me to chat in threads. Just type your message and I'll reply.
You don't have enough credits to chat. Use /balance to see how many credits you have left. Buy a subscription tier to get more credits. Join our server here: https://discord.gg/JCnxEaE3Mx
Can you make it so "while" is true
You don't have enough credits to chat. Use /balance to see how many credits you have left. Buy a subscription tier to get more credits. Join our server here: https://discord.gg/JCnxEaE3Mx
How many credits do you need