我认为使用+=
总计会对结果求和,但是我重新插入后重置了所有内容。
import java.util.Scanner;
public class Week3_Lab {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
int product;
int amount;
while(true){
System.out.print("Enter the product number(1-3): ");
product = input.nextInt();
if (product == -1){
break;
}
System.out.print("Enter the total amount of product: ");
amount = input.nextInt();
num(product, amount);
}
}
public static int num(int product , int amount){
double total_1 = 0;
double total_2 = 0;
double total_3 = 0;
switch (product){
case 1 :
total_1 += amount * 2.98;
break;
case 2 :
total_2 += amount * 4.50;
break;
case 3 :
total_3 += amount * 9.98;
break;
}
System.out.println("The total of product 1 is : "+ total_1);
System.out.println("The total of product 2 is : "+ total_2);
System.out.println("The total of product 3 is : "+ total_3);
return product;
}
}
答案 0 :(得分:1)
您的变量total_1, total_2 and total_3
是本地的,不在方法调用之间共享,因此每个调用都被初始化为0。
如果您不希望发生这种情况,请在方法体外定义它们。
static double total_1=0;
static double total_2=0;
static double total_3=0;
public static int num(int product , int amount){
switch (product){
//...
}
//...
}
答案 1 :(得分:0)
您已将total_1
初始化为0,因此输出的程序只是(amount * 2.98)
,如下所示:
total_1 = 0 + (amount * 2.98);
同样的概念也适用于total_2
和total_3
。