2013-09-24 19 views
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循环。如何通过用户输入端while循环

回答

4

你必须在你的while -loop分配repeat所以它成为false如果用户说yes

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

你只需要根据用户的输入设置repeat为true或false。所以最后,将input与yes或no进行比较。像这样的东西可以为你工作:

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

'重复=“是”.equals(输入);'......避免分支。 –

+1

@SilviuBurcea它只是代码可读性。 – GoodSp33d

0

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

while (...) { 

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

不要使用==来比较字符串值 –

+0

对不起......太多C#编码对我来说:) –

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

你,如果你还想要你的代码更加系统化,去搜索有关中断,特别是线程中断,以上这些问题的答案是正确的,找到更加有机的代码并执行它