2014-04-26 20 views
0

我如何以同樣的方式將數字加在一起,就像我打印它們一樣。如何使用(System.out.println(numbers))打印方式將數字添加在一起;數字++;

System.out.println(numbers); 
    numbers++; 

這會打印像這樣。

1 
    2 
    3 
    4 

我怎麼會在一起,將他們加入爲1 + 2 + 3 + 4

這裏是關於這個問題我當前的代碼。 這是我在赫爾辛基大學爲我的MOOC工作的練習,我住在美國,所以很難尋求幫助,因爲8小時的時差。

public static void main(String[] args) { 
    Scanner reader = new Scanner(System.in); 

    System.out.print("Until What?:"); 
    // the user inputs a number here 
    int blockExe = 1; 
    // the blockExe variable is supposed to store a count of how many times the 
    // block has been executed which i belive should be limited to the user input 
    int userIn = Integer.parseInt(reader.nextLine()); 
    int sum = userIn + blockExe; 
    // i am supposed to add the number of block executions the user input 
    // each time adding 1 to the execution so 1+2+3 
    // then printing the sum of those numbers 

    while (blockExe <= userIn) { 
     blockExe += 1; 
     if (blockExe + userIn == sum) { 
      break; 
     } 
    } 
    System.out.println("Sum is:" +sum); 

} 

}

+0

什麼是您的示例輸入以及您獲得了哪些輸出以及您需要什麼輸出? – anirudh

+0

該課程的測試跑步者將測試負數和正數,所以第一個樣本輸入是6,我得到的輸出是4,我需要6,所以它應該算作1 + 2 + 3 = 6 –

回答

1

此代碼是不明確的:

while (blockExe <= userIn) { 
    blockExe += 1; 
    if (blockExe + userIn == sum) { 
     break; 
    } 
} 

也許你想這樣的:

int sum=0; 
for(blockExe = 1;blockExe <= userIn; blockExe ++) { 
    sum+=blockExe; 
} 
+0

我明白了這將起作用,但是我們尚未覆蓋(爲)我們的課程。到目前爲止,只是(如果,否則,如果 - 其他,同時,南,和大部分的數學運算符,變量和一些語法。 –

0

的System.out.println( 「總和是:」 +總和) ;

該行沒有意義。我認爲你試圖輸出的數字應該是blockExe,但是你不清楚你試圖從你的描述中做什麼。嘗試將該行更改爲:

System.out.println(「Sum is:」blockExe);

看看是否讓你更接近你的答案。

相關問題