【发布时间】:2019-10-05 20:37:19
【问题描述】:
Here is a sample of what output should look like!!
我的用于显示购买笔记本电脑订单摘要的程序使用 (1)while 循环来处理多台笔记本电脑,使用 (2)if-else 来获取笔记本电脑名称/价格;或错误消息“无效的选择!再试一次。”,(3)嵌套如果确定笔记本电脑的选择何时有效以继续进行其余处理。以及 (4) 嵌套 if 仅在购买笔记本电脑时打印订单摘要。
当我在选项中输入一个无效数字(如 8)时,if 语句仍然执行,而不是它下面的 else。
当我在选项中输入一个有效数字时,它会询问数量,但是当我输入一个数量时,我如何将该用户输入添加到订单摘要而不是程序返回到循环顶部?
我是 Java 新手,我的代码应该如何生成正确的输出?
这是我当前的代码(JAVA)
public static void main(String[] args) {
char cont='Y';
int qty=0;
int trigger=0;
double total=0;
double subtotal=0;
double tax=0;
double price;
double lineItem=0;
String orderSummary=" ";
String laptop=" ";
Scanner input = new Scanner(System.in);
Calendar dateTime = Calendar.getInstance();
//Displays a list of laptops with prices and asked user for their choice. Prompt #1
int choice = 0;
while (choice >= 0) {
System.out.printf("%nTOP LAPTOPS OF %tY"
+ "%n%n1. %-23s %7s $%,9.2f"
+ "%n2. %-23s %8s %,9.2f"
+ "%n3. %-23s %8s %,9.2f"
+ "%n4. %-23s %8s %,9.2f"
+ "%n5. %-23s %8s %,9.2f"
+ "%n%nEnter your choice: ",
dateTime,
"HP Envy 13", " ", 799.99,
"Asus ZenBook 13 UX333FA", " ", 849.99,
"Dell XPS 13", " ", 989.99,
"Alienware Area 51-m", " ", 1999.99,
"Razer Blade Stealth", " ", 1299.00);
choice = input.nextInt();
if (choice < 6 || choice > 0) {
System.out.printf("Enter the quantity:");
qty = input.nextInt();
} else {
System.out.printf("Invalid choice! Try again.%n%n");
System.out.printf("Enter 'Y' to add a laptop to your purchase or 'N' to exit: ");
cont = input.next().charAt(0);
}
if (cont == 'Y') {
continue;
}
if (cont == 'N') {
System.exit(0);
}
//The following if-else prints a $ sign for the first line item
if (trigger == 1) {
orderSummary += String.format("%n%, -9d %-30s %8s $%,17.2f", qty, laptop, " ", lineItem);
trigger = 0;
} //End else for no $ sign
//The following statement prints the order summary of the laptops purchased.
//This should be done when there are no more laptops to process
if (choice > 0) {
if (choice < 6) {
tax = subtotal * .0825;
total = subtotal + tax;
orderSummary += String.format("%n%n%34s Subtotal %6s %,17.2f"
+ "%n%31s Tax @ 8.25%% %6s %,17.2f"
+ "%n%n%37s TOTAL %5s $%,17.2f%n",
" ", " ", subtotal,
" ", " ", tax,
" ", " ", total);
System.out.printf("%s", orderSummary);
break;
} //End if valid choice range ends print order summary
} //End if valid choice range begins
}
}
【问题讨论】:
-
将问题分成段落。并使用其他特征来突出价值。可读性很重要。
标签: java if-statement while-loop nested-loops