課程作業02 1.
程序設計思想:運用輸入語句輸入循環N個數據,定義int類型數組存放轉換成整形之後的數據值,定義一個int類型變量存儲相加之後的值,進行運算後將結果輸出即可。
程序設計流程圖:
程序源代碼:
package shiyueyixiti;
import javax.swing.JOptionPane;
import java.util.Scanner;
public class shiyueyi {
public static void main(String[] args) {
// TODO 自動生成的方法存根
int i;//用來循環使用
int n;//用來代表輸入數字個數
String a;
a=JOptionPane.showInputDialog( "請輸入需要進行相加的數字個數:" );
//System.out.println("請輸入需要進行相加的數字個數:");
n=Integer.parseInt( a );
String Number[]=new String[n];;//string entered by user
int number[]=new int[n]; // number to add
int sum=0; // 存儲所有number的和
for(i=0;i<n;i++)
{ Number[i] =
JOptionPane.showInputDialog( "Enter "+(i+1)+" integer" );
}
// read in number from user as a string
for(i=0;i<n;i++)
{
number[i] = Integer.parseInt( Number[i] );
}
// convert numbers from type String to type int
// add the numbers
for(i=0;i<n;i++)
{
sum=sum+number[i];
}
// display the results
JOptionPane.showMessageDialog(
null, "The sum is " + sum, "Results",
JOptionPane.PLAIN_MESSAGE );
System.exit( 0 ); // terminate the program
}
}
程序運行截圖:
課程作業02 1.