課堂作業1 多個數字求和
一,設計思想
1,通過簡單的窗口實現多個數字的輸入與輸出。
2,可通過用戶輸入數字的數量來實現多個數字的求和。
3,定義整型數組變量number和字符串型數組變量integer,將輸入的字符串變量賦給整數number,通過循環來實現多個數字的求和。
4,用do……while循環實現是否繼續計算。
二,程序流程圖
三,源程序代碼
package 求和;
import javax.swing.JOptionPane;
public class Sum {
public static void main(String[] args){
int n; //定義求和的數字的數量
String choose;//定義選擇是否繼續的字符串變量
int choice;//定義選擇是否繼續的變量
do
{
int sum=0;//初始化sum
String n1=JOptionPane.showInputDialog("Enter the mount of numbers");
n=Integer.parseInt(n1);//將字符串轉化為數字的數量
int[] number=new int[n];//定義整數數組
String[] integer=new String[n];//定義字符串數組
for(int i=0;i<n;i++){
integer[i]=JOptionPane.showInputDialog
number[i]=Integer.parseInt(integer[i]);//將字符串轉化為數字
sum=sum+number[i];//求和
}
JOptionPane.showMessageDialog(null,"The sum is "+sum,"Result",JOptionPane.PLAIN_MESSAGE);
choose=JOptionPane.showInputDialog("是否繼續?\n 1,繼續 2,退出");
choice=Integer.parseInt(choose);
}while(choice==1);
System.exit(0);
}
}
四,結果截圖
課堂作業1 多個數字求和