如何通过用户输入结束循环

时间:2013-09-24 07:14:10

标签: java if-statement while-loop

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循环。

5 个答案:

答案 0 :(得分:4)

您必须在repeat循环中指定while,以便在用户说false时变为yes

repeat = !input.equalsIgnoreCase("yes"); 

答案 1 :(得分: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 

答案 2 :(得分: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();
    }

答案 3 :(得分:1)

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

答案 4 :(得分:0)

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

while (...) {

   input = ...;
   if (input.equals("Y")) {
     break;
   }
}