2
package cst150zzhw4_worst;

import java.util.Scanner;

public class CST150zzHW4_worst {

    public static void main(String[] args) {
    //Initialize Variables
    double length; // length of room
    double width; // Width of room
    double price_per_sqyd; // Total carpet needed price
    double price_for_padding; // Price for padding
    double price_for_installation; // Price for installation
        String input; // User's input to stop or reset program
    double final_price; // The actual final price
        boolean repeat = true;

    // Create a Scanner object for keyboard input.
    Scanner keyboard = new Scanner(System.in);

        while (repeat)
        {   
        //User Input

    System.out.println("\n" +"What is the length of the room?: ");
    length = keyboard.nextInt();

    System.out.println("What is the width of the room?: ");
    width = keyboard.nextInt();

    System.out.println("What is the price of the carpet per square yard?: ");
    price_per_sqyd = keyboard.nextDouble();

        System.out.println("What is the price for the padding?: ");
        price_for_padding = keyboard.nextDouble();

        System.out.println("What is the price of the installation?: ");
        price_for_installation = keyboard.nextDouble();

        final_price = (price_for_padding + price_for_installation + price_per_sqyd)*((width*length)/9);

        keyboard.nextLine(); //Skip the newline

        System.out.println("The possible total price to install the carpet will be $" + final_price + "\n" + "Type 'yes' or 'no' if this is correct: ");
        input = keyboard.nextLine();

        } 
    }
}

当用户说“是”程序停止并且如果用户说“不”那么程序只是重复时,我将如何做到这一点?我不知道为什么我有这么多麻烦。我已经搜索了4个多小时。我认为我只应该使用一个while循环。

4

5 回答 5

4

repeat您必须在您的while-loop中进行分配,这样false如果用户说yes

repeat = !input.equalsIgnoreCase("yes"); 
于 2013-09-24T07:16:57.540 回答
2

您只需要repeat根据用户输入设置为 true 或 false。所以最后,比较input是或否。像这样的东西对你有用:

if ("yes".equals(input)) 
 repeat = true; // This would continue the loop
else 
 repeat = false; // This would break the infinite while loop 
于 2013-09-24T07:17:20.253 回答
1
    boolean repeat = true;

   // Create a Scanner object for keyboard input.
     Scanner keyboard = new Scanner(System.in);

    while (repeat)
    {   
       -----------------------
       -------------------------
       System.out.println("Do you want to continue:");
       repeat = keyboard.nextBoolean();
    }
于 2013-09-24T07:20:23.367 回答
1

如果你想让你的代码更系统,去搜索中断,特别是线程中断,上面这些答案是正确的,找到更有机的代码并实现它

于 2013-09-24T07:23:28.813 回答
0

您可以使用break语句退出 while 循环。

while (...) {

   input = ...;
   if (input.equals("Y")) {
     break;
   }
}
于 2013-09-24T07:17:51.437 回答