java- 随机生成10个数,填充一个数组并计算数组的和

随机生成10个数,填充一个数组,然后用消息框显示数组内容,接着计算数组元素的和,将结果也显示在消息框中。

1.设计思路

random随机生成10个数,赋值到数组中,然后对数组里的数进行相加,采用JOptionPane.showMessageDialog消息框进行输出。

2.程序流程图

3.源程序代码

 1 import javax.swing.*;
 2 
 3 public class Array {
 4     
 5     
 6     public static void main(String[] args) {
 7 
 8         // TODO Auto-generated method stub
 9 
10         String output = "";
11         
12         int n[]=new int[10];
13         
14         for(int i=0;i<10;i++)
15         {
16             n[i]=(int) ( Math.random() *100 );
17         }
18 
19        
20 
21         int a=0;
22 
23         output += "数组为:
 ";
24 
25         for(int i=0;i<n.length;i++)
26 
27             output += n[i] + "
";
28 
29         output += "数组和为:";
30 
31         for(int i=0;i<n.length;i++)
32 
33             a += n[i];
34 
35         output += a;
36 
37         JTextArea outputArea = new JTextArea( 11, 10 );
38 
39           outputArea.setText( output );
40 
41         JOptionPane.showMessageDialog( null, outputArea, "Initializing an Array with a Declaration",JOptionPane.INFORMATION_MESSAGE );//以对话框的形式出现
42 
43         System.exit( 0 );
44 
45     }

4.结果截图

5.编程总结

int n[]=new int[10];[开辟新数组]
Math.random()[产生随机数]
JOptionPane.showMessageDialog()[对消息进行消息框的输出]
原文地址:https://www.cnblogs.com/suifengye/p/6036411.html