本文最終結果大概是這樣的,使用java技術隨機生成10個數,然后填充一個數組并在消息框中顯示數組內容,接著對數組求和輸出,將結果顯示在消息框中。
設計思路:可以先用Math.Random()*1000生成1000以內隨機數,然后依次存入數組中,然后讀取數組,輸出隨機數,同時進行加法計算,最后將所有結果以消息框形式輸出。
程序流程圖:
源代碼:
package 隨機數求和;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import javax.swing.*; public class Sum { public static void main(String args[]) { String output= "10個1000以內的隨機數為:\n" ; int sum= 0 ; int a []= new int [ 10 ]; for ( int i = 0 ;i< 10 ;i++) { a[i]=( int ) (Math.random()* 1000 ); output += " " +a[i]; sum += a[i]; } output += "\n\n十個數的和是:" +sum; JOptionPane.showMessageDialog( null ,output, "結果" , JOptionPane.PLAIN_MESSAGE); } } |
結果截圖:
總結:利用Math.Random()*n可以生成任意n內的隨機數,最后利用JOptionPane.showMessageDialog(null,output," “JOptionPane.PLAIN_MESSAGE);
可以再對話框中輸出結果。
以上是實現Java生成10個1000以內的隨機數并用消息框顯示數組內容然后求和輸出的全部內容,希望大家喜歡。