隨機生成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()[對消息進行消息框的輸出]