Home > Mobile >  How do I accumulate a sum of a series of input values?
How do I accumulate a sum of a series of input values?

Time:11-19

//Modify the program from the previous exercise, so that it displays just the sum of all of the numbers from one to the input number. Be sure to test your program with several inputs.

// Example5.java

import java.util.Scanner;

public class Example5 {

    public static void main(String[] args) {
        int count = 0;

        Scanner in = new Scanner(System.in);

        System.out.println("Enter a number: ");
        int number = in.nextInt();
        while (count <= number) {
            System.out.println(count);
              count;

        }
    }

Given that code I have to modify the program that it displays the sum from 1 to the input number.

CodePudding user response:

You asked

How do I accumulate a sum of a series of input values?

In the mentioned practice you need to separate your numbers with whitespace, there are many more advance approach like using IntStream api.

public class Example5 {
    public static void main(String[] args) {
        int sum = 0;
        System.out.println("Add your numbers to sum: ");
        Scanner in = new Scanner(new Scanner(System.in).nextLine());
        while (in.hasNext()) {
            sum  = in.nextInt();
        }
        System.out.println(sum);
    }
}

CodePudding user response:

This code gives an output based on the statement, "Given that code I have to modify the program that it displays the sum from 1 to the input number."

import java.util.Scanner;

public class Example5 {

    public static void main(String[] args) {
        int sum = 0, number;
        Scanner in = new Scanner(System.in);

        System.out.println("Enter a number: ");
        number = in.nextInt();

        for (int i = 1; i <= number; i  ) sum  = i;

        System.out.println(sum);
    }
}
  • Related