1. 程式人生 > 其它 >004Java入門——JAVA的特性和優勢

004Java入門——JAVA的特性和優勢

順序結構  if
public static void main(String[] args) {
//建立一個掃描器物件,用於接受鍵盤資料)
Scanner scanner = new Scanner(System.in);
System.out.println("使用nextline接收:");
//判斷使用者有沒有輸入字串
if(scanner.hasNextLine()){
//使用next/nextline接收
String str = scanner.nextLine();
System.out.println("輸入的內容為:" +str);
}
//凡是屬於IO流的類如果不關閉會一直佔用資源,要養成好習慣用完就關閉
scanner.close();

}
next以空格作為結束

nextline以回車作為結束(多用)

選擇結構 else

public class Demo03 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
        //從鍵盤接受資料
        int i = 0;      
float f =0.0f;
System.out.println("請輸入整數");
//如果。。。那麼  
if (scanner.hasNextInt()){
i = scanner.nextInt();
System.out.println("整數資料:"+i);
}
else {
System.out.println("輸入的不是整數資料");
}
//如果。。。那麼
System.out.println("請輸入小數");
if(scanner.hasNextFloat()){
f = scanner.nextFloat();
System.out.println("小數資料:"+f);
}
else{
System.out.println("輸入的不是小數資料:");
}
        scanner.close();
}
}

迴圈結構 while

public class Demo04 {
public static void main(String[] args) {
//我們可以輸入多個數字,並求其總和與平均數,每輸入一個數字用回車確認,通過輸入非數字來結束輸入並輸出執行結果
Scanner scanner= new Scanner(System.in);
System.out.println("請輸入資料");

//和
double sum = 0;
//計算輸入了多少個數字
int m = 0 ;
//通過迴圈判斷是非還有輸入,並在裡面對每一次進行求和和統計
while (scanner.hasNextDouble()){
double x = scanner.nextDouble();
m = m+1;
sum = sum+1;
}

System.out.println(m+"個數的和為"+sum);
System.out.println(m+"個數的平均值為"+(sum/m));

scanner.close();
}
}