循環(huán)語句
//我們可以輸入多個(gè)數(shù)字秩贰,并求其總和和平均數(shù),每輸入一個(gè)數(shù)按回車確認(rèn)柔吼,通過非數(shù)字
? ? ? ? //來結(jié)束并輸出結(jié)果
? ? ? ? Scanner scanner = new Scanner(System.in);
? ? ? ? //和
? ? ? ? double sum = 0;
? ? ? ? //計(jì)算輸入多少數(shù)字
? ? ? ? int m = 0;
? ? ? ? //通過循環(huán)判斷是否有輸入毒费,并在里面對每一次進(jìn)行求和和統(tǒng)計(jì)
? ? ? ? while (scanner.hasNextDouble()) {
? ? ? ? ? ? double x = scanner.nextDouble();
? ? ? ? ? ? //
? ? ? ? ? ? m = m + 1;//m++
? ? ? ? ? ? sum = sum + x;
? ? ? ? }
? ? ? ? ? ? System.out.println("個(gè)數(shù)和為"+ sum);
? ? ? ? ? ? System.out.println("個(gè)數(shù)平均值"+(sum / m));
? ? ? ? scanner.close();
if語句
Scanner scanner = new Scanner(System.in);
? ? ? ? ? ? int i = 0;
? ? ? ? ? ? float f = 0.0f;
? ? ? ? System.out.println("請輸入整數(shù):");
? ? ? ? if (scanner.hasNextInt())
? ? ? ? {
? ? ? ? ? ? i = scanner.nextInt();
? ? ? ? ? ? System.out.println("整數(shù)數(shù)據(jù):" + i);
? ? ? ? }else{
? ? ? ? ? ? System.out.println("輸入的數(shù)據(jù)不是整數(shù)數(shù)據(jù)!");
? ? ? ? }
這兩差不多
? ? ? ? if (scanner.hasNextInt())
? ? ? ? {
? ? ? ? ? ? f = scanner.nextInt();
? ? ? ? ? ? System.out.println("小數(shù)數(shù)據(jù):" + f);
? ? ? ? }else{
? ? ? ? ? ? System.out.println("輸入的數(shù)據(jù)不是小數(shù)數(shù)據(jù)!");
? ? ? ? }
? ? ? ? ? ? scanner.close()