1. 程式人生 > >D:不定長整數序列求和問題

D:不定長整數序列求和問題

D:不定長整數序列求和問題

(輸入檔案: 0. in輸出檔案: estdout. Dc2)
Jan最近正在學習最簡單的程式設計技術,熟練掌握了定長度(資料個數已知)的整數
加法程式設計方法後,他試圖解決不定長度(資料個數不確定)整數序列求和的問題。由於
沒有找到把未知個數的資料求和的方法,Jare 陷入了苦惱之中。作為程式設計師的你,能否寫
一個用於不定長整數序列求和的程式給他提供幫助呢?

輸入資料:

第行輸入一個整數n表示測試案例的個數。接下來的口行,每行由1到若干個整數構
成,兩個整數之間用空格分開,用回車結束資料序列的輸入。

輸出資料:

對於每一行用於求和的整數,輸出一個和數值。輸出的形式為: Sum=Xxx (其中,XXX是具體的求和資料)

樣例輸入:

2
2 55 77
10 20 30 40 50 60 70 80 90 100

樣例輸入:

sum=134
sum=550


Java程式碼

public class Main {
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		int n;
		String str = null;
		Scanner input = new Scanner(System.in);
		String x = input.nextLine();
		n = Integer.parseInt(x);

		for(int i = 0; i < n; i++) {
			str = input.nextLine();
			show(str);
		}

	}

	private static void show(String str) {
		int sum = 0;
		String[] s = str.split(" ");
		for(int i = 0; i < s.length; i++) {
			sum += Integer.parseInt(s[i]);
		}
		System.out.println("sum="+sum);
	}

}