2017-04-10 45 views
-4

我以为使用了+=总计会对结果进行求和,但他在我再次插入后重新设置了所有值。开关柜中的(+ =)功能不起作用

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

您提供的'product'和'amount'的值是多少?它是如何“不工作”? –

+1

我假设你想在方法定义之外移动'double total_X'定义,以便它们不会每次都被清除。 –

+0

因为根据问题的结果应该是这样的: – Learning

回答

0

你初始化你total_1为0,因此该方案是输出仅仅是(amount * 2.98)如下图所示:

total_1 = 0 + (amount * 2.98); 

相同的概念被应用于total_2total_3为好。

+0

我试过了,但也不起作用,好像现在的方法是把变量从方法中拿出来。 – Learning

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

非常感谢,它的工作原理 – Learning