MattGotJava - 21 days ago 5x

Java Question

This is one of my very first java projects and I'm trying to make a mini calculator and right now I'm working on addition.

What I want it to do is like it will ask the user how many number they want to add and then after you type all the numbers, and the java code has to get all the numbers that inputted.

Here's the addition part that doesn't work so far:

`private static void Addition() { //I already added the Scanner plugin`

System.out.println("How many numbers would you like to add?");

Scanner adds = new Scanner(System.in);

int addsput = adds.nextInt();

Scanner numa = new Scanner(System.in);

for(int addloop=1; addloop>addsput; addloop++) {

int numaput = adds.nextInt();

//somehow I want to get all the numbers

}

//Here I want to add all the numbers they typed

}

So I hope you get the idea. Any help would be great, because I've been searching for about an hour to get this figured out. Thanks.

Answer

You have two options, either read the values into an array, or find the sum as you read the values.

You only need one `Scanner`

object, and your `for`

loop had some issues:

```
private static void addition() {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers would you like to add?");
int amountNumbers = input.nextInt();
int sum = 0;
for (int counter = 0; counter < amountNumbers; counter++) {
sum += input.nextInt();
}
System.out.println("Sum: " + sum);
}
```

Using an array:

```
private static void addition() {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers would you like to add?");
int[] numbers = new int[input.nextInt()];
for (int index = 0; index < numbers.length; index++) {
numbers[index] = input.nextInt();
}
int sum = 0;
for (int index = 0; index < numbers.length; index++) {
sum += numbers[index];
}
System.out.println("Sum: " + sum);
}
```

Here is a more advanced way to do it using `IntStream`

from Java 8:

```
private static void addition() {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers would you like to add?");
int amountNumbers = input.nextInt();
int sum = IntStream.generate(input::nextInt)
.limit(amountNumbers)
.sum();
System.out.println("Sum: " + sum);
}
```

Source (Stackoverflow)

Comments