I'm solving a problem to find all the multiples of 3 and 5 within a number that is inputted from the user.
I want to show all the multiples and their sum to the user.
I can't find a way to add the values to the array containing the multiples.
Here is the code:
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.*;
public class application {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Input the number from user:
System.out.println("Enter a number to calculate the sum of all the multiples of 3 or 5 below it: ");
int number = input.nextInt();
int i = 1;
int[] arr = {};
System.out.println("The multiples of 3 and 5 below the number " + number + " are: ");
while(i < number) {
if (i % 3 == 0 || i % 5 == 0 ) {
System.out.print(i + ",");
arr = Arrays.copyOf(arr, arr.length + 1);
arr[arr.length - 1] = i;
}
i++;
}
int sum = IntStream.of(arr).sum();
System.out.println("The sum of these multiples is: " + sum);
//Thank you :D
}
}
question from:
https://stackoverflow.com/questions/65837541/appending-number-values-to-an-array-in-java 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…