随机数

题目要求:

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

要求将设计思路、程序流程图、源程序代码、结果截图、编程总结等发表到博客园。

设计思路:

定义一个10个整数数的数组,利用for循环、Random类进行随机数赋值,同时将随机数相加,然后利用JTextArea类进行格式转换,最后利用JOptionPane.showMesssageDialog进行消息框输出。

程序流程图:

 

源程序代码:

import java.util.Random;
import javax.swing.*;
public class 随机数 {
public static void main(String[] args)
{
    int[]a=new int[10];
    int sum=0;
    for(int i=0;i<a.length;i++)
    {
        Random d=new Random();
        a[i]=d.nextInt(100);
        sum+=a[i];
    }
    String out="   i  "+" 	   "+" 值    
";
    for(int i=0;i<a.length;i++)
    {
        out+="  "+i+"    	   "+a[i]+"
";
    }
    out+="………………………………
"+   "  和: "+"	  "+ sum;
     JTextArea outputArea = new JTextArea( 11, 10 );
     outputArea.setText(out);
      JOptionPane.showMessageDialog( null, outputArea,
                 "Initializing an Array with a Declaration",
                 JOptionPane.INFORMATION_MESSAGE );
}
}

结果截图:

 

编程总结:

加深了对数组和随机数用法的了解,随机数Random类,nextInt()调用整数随机数,nestIntNUM),产生的随机数从零到NUM,包括零,但不包括NUMnextDouble()产生一个双精度浮点型的随机数;nextFloat()产生一个单精度浮点型的随机数。

原文地址:https://www.cnblogs.com/cchjl/p/4931138.html