1

我刚刚开始学习Java,我需要使用switch语句,但我需要跟踪每个案例的所有计算值,然后需要将其相加。我该怎么做?

这是我现在的代码

            switch(productNo)
            {
                case 1:
                    lineAmount1 = quantity * product1;
                    orderAmount = +lineAmount1;
                    textArea.append(productNo +"\t"
                            + quantity + "\t" 
                            + "$" + lineAmount1 +"\t"
                            + "$" + orderAmount + "\n" );


                    break;
                case 2:
                    lineAmount2 = quantity * product2;
                    orderAmount = + lineAmount2;
                    textArea.append(productNo +"\t"
                            + quantity + "\t" 
                            + "$" + lineAmount2 +"\t"
                            + "$" + orderAmount + "\n" );


                    break;

                case 3:
                    lineAmount3 = quantity * product3;
                    orderAmount = +lineAmount3;
                    textArea.append(productNo +"\t"
                            + quantity + "\t" 
                            + "$" + lineAmount3 +"\t"
                            + "$" + orderAmount + "\n" );

                    break;

                case 4:
                    lineAmount4 = quantity * product4;
                    orderAmount = +lineAmount4;
                    textArea.append(productNo +"\t"
                            + quantity + "\t" 
                            + "$" + lineAmount4 +"\t"
                            + "$" + orderAmount + "\n" );

                    break;

                case 5:
                    lineAmount5 = quantity * product5;
                    orderAmount = +lineAmount5;
                    textArea.append(productNo +"\t"
                            + quantity + "\t" 
                            + "$" + lineAmount5 +"\t"
                            + "$" + orderAmount);

                    break;

            }
4

2 回答 2

0

您可以在循环中执行相同的操作,而不是使用 switch-case,因为在这些情况下您没有做任何不同的事情 -

int lineAmount = 0;
int orderAmount = 0;
for (int product : products) {
lineAmount = quantity * product;
orderAmount += lineAmount;
textarea.append(productNo +"\t"
                        + quantity + "\t" 
                        + "$" + lineAmount +"\t"
                        + "$" + orderAmount + "\n" );
}

此代码基于以下假设:您有一个产品列表,您在其中调用 switch case...整个代码可以替换为...如果您需要将特定产品与特定编号相关联,那么您可以使用 Enum 并在循环内使用它。

于 2013-06-15T16:58:29.497 回答
0

从您的问题中不清楚您在寻找什么,但我会猜测一下。如果您尝试获取五个项目中的每个项目的总和以及总和,则可以使用一个数组作为总行,在 switch 语句之前的某个位置定义:

double[] lineTotals = new double[5];
double orderTotal = 0;

然后您可以将每个项目的值放入数组中,记住索引从 0 而不是 1 开始:

switch(productNo) {
    case 1:
        lineAmounts[0] = quantity * products[0];
        orderAmount = +lineAmounts[0];
        textArea.append(productNo +"\t"
            + quantity + "\t" 
            + "$" + lineAmount1 +"\t"
            + "$" + orderAmount + "\n" );
        break;

    case 2: ... etc ...
}
于 2013-06-15T17:02:37.480 回答