猿问

如何将一个部分与另一个部分链接

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

    }

}

这就是给我带来麻烦的原因。


杨__羊羊
浏览 109回答 1
1回答

ITMISS

首先,int =a不是一个有效的表达式。它应该是int a;因为你想从100给定值添加下一个数字,你需要将这些值添加到总和中,例如sum = sum+number.这是一个代码片段:&nbsp; &nbsp; Scanner myInput = new Scanner(System.in);&nbsp; &nbsp; // correct declaration&nbsp; &nbsp; int a;&nbsp; &nbsp; // initialize sum with zero.&nbsp; &nbsp; int sum=0;&nbsp; &nbsp; System.out.print("Enter first integer: ");&nbsp; &nbsp; a = myInput.nextInt();&nbsp; &nbsp; //for simplicity,start value n from a and loop until n reaches a+100.&nbsp; &nbsp; for (int n = a; n <= 100+a; n++) {&nbsp; &nbsp; &nbsp; &nbsp; sum = sum + n;&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println("Sum = "+ sum);
随时随地看视频慕课网APP

相关分类

Java
我要回答