2016-01-20 37 views
1

嗨,大家好我今天對這個程序有了一些幫助,基本上我想要的是1-200的數組,然後用戶輸入1到200之間的數字 然後將拉曼數加在一起並輸出答案。用戶輸入後剩餘數組的總和

例如用戶輸入100,然後將100-200的數字加在一起並輸出答案。

使用我迄今爲止的代碼,它總是輸出0作爲答案。有任何想法嗎? 謝謝。

//Importing scanner 
import java.util.Scanner; 
//Class name 
class programfive{ 

    //Main method 
    public static void main (String[]args){ 
     //declaring and inizialising scanner 
     Scanner input = new Scanner (System.in);  
     //Declaring and inizialising variables 
     int userInput = 0; 
     int sum = 0; 
     //Array initializer 
     int array[] = new int [201]; 
     //Prompt for user input 
     System.out.print("Please enter a value between 1 and 200: "); 
     userInput = input.nextInt(); 
     //For loop - starts at number user inputted, stops when reaches 200, increments by 1. 
     for (int i = userInput; i<=200; i++) 
     { 
      sum += array[i]; 
     } 
     System.out.println(sum); 
    }//End of main method 
}//End of class 
+0

你想添加100-200的數字在一起或數組中包含的數字索引100-200? – asiew

+0

您是否在其他地方使用用戶輸入或只是爲了完成這個和?如果它只是總和,我會建議甚至不使用數組。 – gonzo

+0

關於代碼中評論數量的一般評論:將來嘗試僅評論不明確的內容,否則重要評論將被忽略。在10條評論中,只有第三條才能解釋循環條件。 – SaschaM78

回答

2

因爲您沒有在數組中放入任何東西,所以它在每個索引處都包含默認的int值,即0。

你有你想要的值來填充它,這樣數組[0]包含0,數組[1]包含1等。

int array[] = new int [201]; 

for(int i=0; i<array.length;i++) 
    array[i] = i; 

此外,您可以擺脫陣列並得到同樣的結果:

for (int i = userInput; i<=200; i++) 
    { 
     sum += i; 
    } 
+0

謝謝!它的工作原理和我理解循環的條件,但只是爲了我自己的理解什麼是總和+ =我;在做什麼? – bigbeans

+0

_sum + = i_表示_sum = sum + i_,所以它將i加到總和上。 – Berger

1

你需要先初始化數組,或者改變總和環路:

for (int i = userInput; i<=200; i++) 
{ 
    sum += i; 
} 
0

未測試但應該工作:

public static void main(String[]args) { 
    Scanner input = new Scanner(System.in);  
    int userInput = 0; 
    int sum = 0; 
    System.out.print("Please enter a value between 1 and 200: "); 
    userInput = input.nextInt(); 
    for (int i = userInput; i<=200; i++) 
     sum += i 
    userInput.close(); 
    System.out.println(sum); 
} 
+1

它不會:你在'sum + = i'後忘了分號:) –

0

你忘了現在填充的數字陣列的所有數組元素都指向0

默認值數組聲明和你的好之後添加這行代碼去:

for(int i=0;i<array.length;i++) 
      array[i]=i;