嗨,大家好我今天對這個程序有了一些幫助,基本上我想要的是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
你想添加100-200的數字在一起或數組中包含的數字索引100-200? – asiew
您是否在其他地方使用用戶輸入或只是爲了完成這個和?如果它只是總和,我會建議甚至不使用數組。 – gonzo
關於代碼中評論數量的一般評論:將來嘗試僅評論不明確的內容,否則重要評論將被忽略。在10條評論中,只有第三條才能解釋循環條件。 – SaschaM78