随机数组求和

题目要求:

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

设计思路:

    创建一个长度为10的double型数组,调用Java.util.Random包定义Random对象,利用方法nextInt(100);在通过for循环、Random类进行随机数赋值得到1-100间的随机数。在将数组里的数相加。最后在用JOptionPane.showMesssageDialog进行消息框输出。

程序流程图:

源程序代码:

package qaq;
import java.util.Random;

import javax.swing.*;

public class qaq {
public static void main(String[] args) {
int []a=new int[10];
Random d=new Random();
int sum=0;
String output="";
for(int i=0;i<a.length;i++)
{
a[i]=d.nextInt(100);
output=output+a[i]+" ";
}
for(int i=0;i<a.length;i++)
{
sum+=a[i];
}
String output1=" 和为:"+sum;

JOptionPane.showMessageDialog( null, output+output1,
"随机数组求和:",
JOptionPane.INFORMATION_MESSAGE );
}
}

结果截图:

编程总结:

学会并熟练应用数组的计算和随机数的产生,并良好的利用消息框,输出。

原文地址:https://www.cnblogs.com/mengqimoli/p/4931516.html