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

Java 如何通过用户输入结束while循环,java,if-statement,while-loop,Java,If Statement,While Loop,当用户说“是”时,程序将停止,如果用户说“否”,则程序将重复,我如何做到这一点?我不知道为什么我有这么多麻烦。我已经找了4个多小时了。我想我应该只使用一个while循环 您必须在while-循环中指定repeat,这样,如果用户说yes,它就会变成false: package cst150zzhw4_worst; import java.util.Scanner; public class CST150zzHW4_worst { public static void main(St

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

您必须在
while
-循环中指定
repeat
,这样,如果用户说
yes
,它就会变成
false

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

        } 
    }
}

您只需根据用户输入将
repeat
设置为true或false。因此,最后,将
输入
与是或否进行比较。类似的方法适用于您:

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

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

if ("yes".equals(input)) 
 repeat = true; // This would continue the loop
else 
 repeat = false; // This would break the infinite while loop 

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

不要用==来比较字符串值,对我来说太多的C#编码:)
repeat=“yes”。equals(输入)。。。避免分支。
while (...) {

   input = ...;
   if (input.equals("Y")) {
     break;
   }
}
    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();
    }