嵌套的 While 循环和嵌套的 if…else 结构在 Java 中的应用。

huangapple go评论66阅读模式
英文:

Nested While Loops and nested if...else Java

问题

import java.util.Scanner;

public class Shopping {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        // Initialize variables
        double total = 0; // grand total of items and their amounts
        double itemNum = 0; // corresponding item number
        int itemAmount = 0; // quantity of item
        double itemPrice = 0; // price of selected itemNum

        // Offer user product menu
        System.out.printf("以下物品可供购买:%n"
                + "物品 1:$101.00%n物品 2:$119.25%n物品 3:$160.75%n物品 4:$203.00%n"
                + "物品 5:$109.12%n");
        System.out.printf("/////////////////%n%n");

        // Prompt user for item they want to buy
        System.out.println("输入您想购买的物品编号,如 1、2、3 等,或输入 00 退出。");
        itemNum = input.nextDouble();
        while (itemNum != 00) {
            if (itemNum == 1) {
                itemPrice = 101.00;
            } else if (itemNum == 2) {
                itemPrice = 119.25;
            } else if (itemNum == 3) {
                itemPrice = 160.75;
            } else if (itemNum == 4) {
                itemPrice = 203.00;
            } else if (itemNum == 5) {
                itemPrice = 109.12;
            }

            // Prompt user for quantity of the item they want to purchase
            System.out.println("输入您想购买的物品数量,或输入 00 退出。");
            itemAmount = input.nextInt();

            while (itemAmount != 0) {
                total += itemPrice * itemAmount;
                System.out.println("输入您想购买的物品编号,如 1、2、3 等,或输入 00 退出。");
                itemNum = input.nextDouble();
                if (itemNum == 00) {
                    System.out.printf("您所购物品的总价为:$%.2f%n", total);
                    break;
                }
                if (itemNum == 1) {
                    itemPrice = 101.00;
                } else if (itemNum == 2) {
                    itemPrice = 119.25;
                } else if (itemNum == 3) {
                    itemPrice = 160.75;
                } else if (itemNum == 4) {
                    itemPrice = 203.00;
                } else if (itemNum == 5) {
                    itemPrice = 109.12;
                }

                System.out.println("输入您想购买的物品数量,或输入 00 退出。");
                itemAmount = input.nextInt();
            }
        }
    }
}
英文:

I am having issues with my nested while loops working.
The assignment is to ask the user for input on what item they want to purchase and then ask how many of that item they want. The end result is for the total of all items chosen once they no longer want to purchase items.

Just to mention, I wanted to use an array instead of nested if...else statements for the price of the items but we have not learned arrays yet in class.

The loop pauses after input of 1/2/3/4/5 but will successfully terminate if the input is 00.

import java.util.Scanner;
public class Shopping {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
//initialize variables
double total = 0; // grand total of items and their amounts
double itemNum = 0;// corresponding item number
int itemAmount = 0;// quantity of item
double itemPrice =0; //price of selected itemNum
//offer user product menu
System.out.printf("The following items are available to purchase: %n"
+ "Item 1: $101.00%nItem 2: $119.25%nItem 3: $160.75%nItem 4: $203.00"
+ "%nItem 5: $109.12%n " );
System.out.printf("/////////////////%n%n");
//prompt user for item they want to buy
System.out.println("Enter what item you want to purchase as 1, 2, 3, etc. OR "
+ "enter 00 to quit.");
itemNum = input.nextDouble();
while (itemNum != 00){
if (itemNum == 1){
itemPrice = 101.00;
}
else {
if (itemNum ==2){
itemPrice = 119.25;
}
else {
if (itemNum ==3){
itemPrice = 160.75;
}
else {
if (itemNum ==4) {
itemPrice = 203.00;
}
else {
if(itemNum ==4){
itemPrice = 109.12;
}
else {
if (itemNum == 5){
itemPrice = 109.12;
}    
}
while (itemNum  <= 5){
System.out.println("Enter how many of the item you want to purchase OR "
+ "enter 00 to quit.");
itemAmount = input.nextInt();
while (itemAmount != 00){
{
total = itemNum * itemAmount;
}
}
}
}
}
}
}
}
if (itemNum == 00){
System.out.printf("Your total for your items is: $%.2f%n", total);
}
}
}
```
</details>
# 答案1
**得分**: 1
哎呀,从哪里开始呢。
## 00 并不是你想象的那样。
`00` 是一个八进制数,与 0 的确切、精确相同的值。双精度浮点数无法表示用户仅输入 `0` 或 `00` 之间的差异。实际上,如果用户输入 `000.0000`,最终仍然会变成 0。你的 `== 00` 代码“有效”,但暗示了一些不正确的事情。直接写 `== 0`。如果你希望循环在输入精确为 `00` 时结束,而不是其他任何情况,你**不能**使用 `.nextDouble()`。使用 `.next()`,检查字符串输入,并在确定它不是 `00` 后使用 `Double.parseDouble` 将其转换为双精度浮点数,如果确实需要的话。
此外,你要求的数字是具体的。输入“我想要第4.591824号物品”没有意义。那么为什么要调用 `.nextDouble()`?应该调用 `.nextInt()`。
## 那是可怕的 if/else 格式。
你所做的一切就是将项目映射到价格。有更好的方法来做:
```java
// 在顶层(与你的方法定义并列):
private static final Map<Integer, Double> PRICES = Map.of(
1, 101.00,
2, 119.25,
3, 160.75,
4, 203.00,
5, 109.12);
// 稍后在一个方法中
double price = PRICES.getOrDefault(itemNum, 0.0);
// price 现在是价格。如果项目不在其中,就是 0.0。

就这样,用一个映射消除了整个丑陋的混乱,而且现在还可以轻松从数据文件或数据库中填充映射。

如果这对你在 Java 的初步学习中来说有点困难,可以创建一个辅助方法:

public double getPriceForItem(int itemNum) {
    if (itemNum == 1) return 101.00;
    if (itemNum == 2) return 119.25;
    if (itemNum == 3) return 160.75;
    if (itemNum == 4) return 203.00;
    if (itemNum == 5) return 109.12;
}

你的代码难以阅读,而且已经让你陷入困境。

你的代码将检查 itemNum 是否为 4,并将 itemPrice 设置为 203.00。如果不是,它将再次检查 itemNum 是否为 4,然后将价格设置为 109.12。这显然是胡言乱语,你的眼睛可能没有注意到这个明显的错误,因为你的代码很混乱。这就是混乱代码的代价,它应该是一个很好的教训,让你明白为什么不要让代码难以追踪。

使用 while 循环进行输入

然后,你开始使用 while 循环来询问单个输入(比如“你想买多少个”)。这并不是 while 循环的用途。

这段代码应该只有一个 while 循环。不是三个。

英文:

Oof, where to start.

00 doesn't do what you think it does.

00 is an octal number that... is the exact, precise same value as 0. There is no way for a double to represent the difference between a user entering just 0 or 00. In fact, if the user enters 000.0000, that's still going to end up being just a 0. Your == 00 code 'works', but suggests something that isn't true. Just write == 0. If you want the loop to end when the input is precisely 00 and not if it is anything else, you cannot call .nextDouble(). Call .next(), check the string input, and Double.parseDouble it (once you determine it wasn't 00) to get to a double, if you must.

Furthermore, the number you're asking for is concrete. Entering "I want item #4.591824" makes no sense. So why are you calling .nextDouble()? Call .nextInt().

That's a horrible if/else formatting.

all that you're doing is mapping an item to a price. There are MUCH nicer ways to do this:

// at the top level (as a sibling to your method defs):
private static final Map&lt;Integer, Double&gt; PRICES = Map.of(
1, 101.00,
2, 119.25,
3, 160.75,
4, 203.00,
5, 109.12);
// later in a method
double price = PRICES.getOrDefault(itemNum, 0.0);
// price is now the price. or 0.0 if the item wasn&#39;t in there.

There. Got rid of the whole ugly mess with one map, which incidentally now is also quite easy to fill off of a data file or a database or whatnot.

If that's a bridge too far for your first steps in java, make a helper method:

public double getPriceForItem(int itemNum) {
if (itemNum == 1) return 101.00;
if (itemNum == 2) return 119.25;
if (itemNum == 3) return 160.75;
if (itemNum == 4) return 203.00;
if (itemNum == 5) return 109.12;
}

Your code is unreadable and it already messed you up.

Your code will check if itemNum is 4, and set itemPrice to 203.00. If that's not it, it will check if itemNum is 4, and then set price to 109.12. Which is obviously gobbledygook, and presumably your eyeballs did not see this obvious messup because you've made messy code. That's the cost of messy code, and it should be a good lesson as to why you don't want code your eyeballs can no longer track.

while loops for input

You then start using while loops to ask for a single bit of input (such as 'how many do you want to buy'. That's not what while loops are for.

This code should have exactly 1 while loop. Not 3.

huangapple
  • 本文由 发表于 2020年9月21日 09:42:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/63985182.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定