Java implements random array output and sum
Problem description:
Randomly generate 10 numbers, fill an array, and then use the message box to display the array content, then calculate the sum of the array elements, and display the results in the message box.
Design ideas:
Use the Random class in java.util to get random numbers. After storing it into the array, define an object result of the String class, use the for loop to store the content of the array to be output to the result and sum it; then use the JoptionPane class in javax.swing to create a message box for the result output.
source code:
import java.util.*;import javax.swing.*;public class SumRandom { public static void main(String[] args) { // TODO Auto-generated method stub long num[] = new long[10]; // Declare the array type and size; String result = ""; // Store the output result of the array content, the initial value is an empty string long sum = 0; // and Random in = new Random(System.currentTimeMillis()); // Create an object reference of the Random class in for(int i = 0; i < 10; i++) { // Sum and save the output result to result num[i] = in.nextLong(); // Assign a random number sum += num[i]; // Sum result += "num["+i+"] = "+num[i]+"/n"; // Storing the array content output result} JOptionPane.showMessageDialog(null, result+"sum = "+sum, "Random number array output and sum", JOptionPane.CLOSED_OPTION); // Create a message box for result output}}Screenshot of the running result:
Programming summary:
To increase code readability, the results to be output can be converted into strings and represented by a String class object.
Thank you for reading, I hope it can help you. Thank you for your support for this site!