好的以下代码(我是新手,请耐心等待我)我希望能够向用户询问问题:
System.out.println("Will the customer be adding any options to the order?");
System.out.println("1. Bed Frame ($39.99)");
System.out.println("2. Pillows ($59.99)");
System.out.println("3. Blankets ($129.99)");
System.out.println("4. No Options added. Enter No");
我知道这是一个循环,但我不知道如何实现这种循环。任何人都可以帮助我并填补空白吗?谢谢。以下是完整的代码
import java.util.Scanner;
public class addons
{
private int Option;
private String Bed_Frame, Pillows, Blankets, No_Options_Added;
private String Name;
private double Price;
public void readInput()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Will the customer be adding any options to the order?");
System.out.println("1. Bed Frame ($39.99)");
System.out.println("2. Pillows ($59.99)");
System.out.println("3. Blankets ($129.99)");
System.out.println("4. No Options added. Enter No");
Option = keyboard.nextInt();
switch (Option)
{
case 1:
Name = "Bed Frame";
Price = 39.99;
break;
case 2:
Name = "Pillows";
Price = 59.99;
break;
case 3:
Name = "Blankets";
Price = 129.99;
break;
case 4:
Name = "No Options Added";
System.out.println("No options added");
Price = 0;
break;
}
}
public void writeOutput()
{
System.out.println(Name);
}
}
答案 0 :(得分:2)
只需添加一个while(true) { ... }
块,您就可以在问题后添加一个条件 - 如果答案是“是” - 请使用break
(不在switch-case块中!)来完成重复循环:
public void readInput() {
Scanner keyboard = new Scanner(System.in);
while (true) { //ADDED THE WHILE LOOP
System.out.println("Will the customer be adding any options to the order?");
System.out.println("1. Bed Frame ($39.99)");
System.out.println("2. Pillows ($59.99)");
System.out.println("3. Blankets ($129.99)");
System.out.println("4. No Options added. Enter No");
Option = keyboard.nextInt();
switch (Option)
{
case 1:
Name = "Bed Frame";
Price = 39.99;
break;
case 2:
Name = "Pillows";
Price = 59.99;
break;
case 3:
Name = "Blankets";
Price = 129.99;
break;
case 4:
Name = "No Options Added";
System.out.println("No options added");
Price = 0;
break;
}
//ADDED EXIT POINT WHEN TO EXIT:
System.out.println("Is that All?");
//read an answer
if (*answer was yes*) break;
} //ADDED A CLOSING BLOCK
}
阅读答案并确定条件应该是一个练习 - 因为它似乎是一个教程任务,我不想破坏乐趣! :)