#GPT-4 Conversation #1103584687630323752

1 messages · Page 1 of 1 (latest)

plush sapphireBOT
tropic ridge
#

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);
    
}

}"

plush sapphireBOT
# tropic ridge How do I get this code to repeat itself after it asks "Would you like to repeat ...

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".

tropic ridge
#

@plush sapphire Can you make it so "while" is true

plush sapphireBOT
plush sapphireBOT
tropic ridge
#

Can you make it so "while" is true

plush sapphireBOT
tropic ridge
#

How many credits do you need