Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
96 views
in Technique[技术] by (71.8m points)

Appending number values to an array in java

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try just adding the multiples together as they are found.

You do not need an array to store them since your code is a) printing out the multiple found and then b) printing out the sum of the multiples


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...