我有這個作業。我很難將第一部分與第二部分聯系起來。這就是我所擁有的。我知道我在某些時候遺漏了一些東西來表明它應該從輸入的數字中添加接下來的 100 個數字。package test;import java.util.Scanner;public class Ex216 { public static void main(String[] args) { // Write a program in Java that reads an integer from the keyboard and makes the sum of the next 100 numbers, showing the result on screen Scanner myInput = new Scanner(System.in); int =a int sum; System.out.print("Enter first integer: "); a = myInput.nextInt(); for (int n = a; n <= 100; n++) System.out.printf("Sum = %d\n", sum); }}這就是給我帶來麻煩的原因。
1 回答

ITMISS
TA貢獻1871條經驗 獲得超8個贊
首先,int =a不是一個有效的表達式。它應該是int a;因為你想從100給定值添加下一個數字,你需要將這些值添加到總和中,例如sum = sum+number.
這是一個代碼片段:
Scanner myInput = new Scanner(System.in);
// correct declaration
int a;
// initialize sum with zero.
int sum=0;
System.out.print("Enter first integer: ");
a = myInput.nextInt();
//for simplicity,start value n from a and loop until n reaches a+100.
for (int n = a; n <= 100+a; n++) {
sum = sum + n;
}
System.out.println("Sum = "+ sum);
添加回答
舉報
0/150
提交
取消