码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-11-06 22:47:43      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:set   stat   length   png   with   imp   流程图   blog   设计   

[实验要求]

随机生成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 += "数组为:\n ";
24 
25         for(int i=0;i<n.length;i++)
26 
27             output += n[i] + "\n";
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()[对消息进行消息框的输出]

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

标签:set   stat   length   png   with   imp   流程图   blog   设计   

原文地址:http://www.cnblogs.com/suifengye/p/6036411.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!