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