简体   繁体   中英

How can I make my do while loop work the way I want it to?

I am trying to make my code loop the prompt to enter rectangle length and width if the user answers yes to the "Continue?:(y/n)" prompt.

It is currently looping the "Continue?:(y/n)" part not the "Enter Length: " and "Enter Width: " part. Any help is appreciated!

import java.util.Scanner;

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

        System.out.println("Welcome to Grand Circus' Room Detail Generator!");

        double length = 0.0;
        double width = 0.0;
        double area = 0.0;
        double perimeter = 0.0;

        System.out.println("Enter Length: ");
        length = scanner.nextInt();

        System.out.println("Enter Width: ");
        width = scanner.nextInt();

        area = length * width;
        perimeter = 2 * (length + width);

        System.out.println("Area: " + area);
        System.out.println("Perimeter: " + perimeter);

        Scanner sc = new Scanner(System.in);
        String response;

        do {
            System.out.print("Continue? (y/n):");
            response = sc.next();
        } while (response.equals("y") || response.equals("Y"));
    }
}

Put

Scanner sc = new Scanner(System.in);
String response;
do {

before

System.out.println("Enter Length: ");

Why would anything outside of your loop body (the stuff between do { and } while (...) ) be repeated?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM