我有这个作业。我很难将第一部分与第二部分联系起来。这就是我所拥有的。我知道我在某些时候遗漏了一些东西来表明它应该从输入的数字中添加接下来的 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
提交
取消