2016-07-30 38 views
0

我正在編寫一個應該計算運行總計的程序,直到用戶輸入999,此時總計(不包括999)應該顯示在屏幕上。如何使用來自掃描儀對象的輸入創建運行總計

我意識到我可能不得不從總數中扣除999,但我的問題是我無法讓它吐出一個總數。我認爲問題是我的Math類沒有正確地從num變量中增加numTotal。請幫忙。 在此先感謝

public class Program { 

public static void main(String[] args) { 

    Scanner kb = new Scanner(System.in); 
    String input = kb.nextLine(); 
    Scanner scn = new Scanner(input); 
    int num = scn.nextInt(); 
    Math math1 = new Math(num,0); 
    while(num != 999){ 
     math1.adder(num); 
     input = kb.nextLine(); 
    } 

    System.out.println(math1.getNumTotal()); 
} //main 

} 

類的結束

public class Math { 

private int num; 
private int numTotal; 

public Math(int num, int numTotal){ 
    this.num = num; 
} 



//get// 

public int getNum(){ 
    return this.num; 
} 

public int getNumTotal(){ 
    return this.numTotal; 
} 

//set// 

public void setNumTotal(int value){ 
    this.numTotal = value; 
} 

public void setNum(int value){ 
    this.num = value; 
} 

//other 
public void adder(int num){ 
    numTotal = numTotal + num; 
} 



} 

類的結束

+0

你覺得下面的回答有用嗎? – Naveen

回答

0

我修改您的代碼如下

import java.util.Scanner; 

public class Program { 
    public static void main(String[] args) { 
     Scanner kb = new Scanner(System.in); 
     int num = 0; 
     Math math1 = new Math(num); 
     while (num != 999) { 
      num = kb.nextInt(); 
      if (num != 999) { 
       math1.adder(num); 
       System.out.println("Total till now:" + math1.getNumTotal()); 
      } 
     } 
     System.out.println(math1.getNumTotal()); 
     System.out.println(math1.getNum()); 
     kb.close(); 
    } 

} 

class Math { 
    private int numTotal; 
    private int num; 

    public Math(int num) { 
     this.num = num; 
    } 

    public int getNum() { 
     return this.num; 
    } 

    public int getNumTotal() { 
     return this.numTotal; 
    } 

    public void setNumTotal(int value) { 
     this.numTotal = value; 
    } 

    public void setNum(int value) { 
     this.num = value; 
    } 

    public void adder(int num) { 
     this.num = num; 
     numTotal = numTotal + this.num; 
    } 

} 

而這裏的日誌

1 
Total till now:1 
2 
Total till now:3 
3 
Total till now:6 
4 
Total till now:10 
999 
10 //math1.getNumTotal() 
4 //math1.getNum() 
+0

什麼!爲什麼downvoted? – Naveen

+0

我不知道誰低調,不是我。感謝您的幫助 –

+0

報告了downvote。希望它被刪除。再次感謝朋友,巨大的幫助。 –