請輸入學(xué)生ID的時候為什么要用while循環(huán),用for循環(huán)可以嗎?
int i=0;
while(i<=3){
System.out.println("請輸入學(xué)生ID");
}
可以換成for循環(huán)嗎?
for(int i=0;i<=3;i++){
System.out.println("請輸入學(xué)生的姓名");
}
int i=0;
while(i<=3){
System.out.println("請輸入學(xué)生ID");
}
可以換成for循環(huán)嗎?
for(int i=0;i<=3;i++){
System.out.println("請輸入學(xué)生的姓名");
}
2015-12-27
舉報
2015-12-27
這個屬于循環(huán)的靈活應(yīng)用,用for循環(huán)也行,但是你感覺用那個比較簡便而又能滿足需求呢?那就用那個吧。
2016-02-23
這里沒有給出完整代碼,
?public void testPut(){
? ? ? ? Scanner in = new Scanner(System.in);
? ? ? ? int i=0;
? ? ? ? while(i<3){
? ? ? ? ? ? System.out.println("請輸入學(xué)生ID:");
? ? ? ? ? ? String ID = in.next();
? ? ? ? ? ? //判斷學(xué)生ID是否被占用
? ? ? ? ? ? Student st = students.get(ID);
? ? ? ? ? ? if(st==null){
? ? ? ? ? ? ? ? System.out.println("請輸入學(xué)生姓名:");
? ? ? ? ? ? ? ? String name = in.next();
? ? ? ? ? ? ? ? //創(chuàng)建一個新的學(xué)生對象實例
? ? ? ? ? ? ? ? Student newStudent = new Student(ID,name);
? ? ? ? ? ? ? ? //通過調(diào)用put方法,添加ID-學(xué)生映射
? ? ? ? ? ? ? ? students.put(ID,newStudent);
? ? ? ? ? ? ? ? System.out.println("成功添加學(xué)生"+students.get(ID).name);
? ? ? ? ? ? ? ? i++; ? ? ?//成功添加了一個學(xué)生
? ? ? ? ? ? }else {
? ? ? ? ? ? ? ? System.out.println("該學(xué)生ID已被占用!");
? ? ? ? ? ? ? ? continue;
? ? ? ? ? ? }
? ? ? ? }
? ? }
我覺得這里用while循環(huán)更合適,因為想要添加三個學(xué)生,但是輸入學(xué)生ID 的時候可能是被占用的,則這次循環(huán)相當(dāng)于無效,用while(i<3)并不表示循環(huán)3次,可能循環(huán)多次,但是有效添加學(xué)生次數(shù)為3次;用for則只循環(huán)3次,可能會出現(xiàn)ID被占用,不一定能添加3個學(xué)生