我想讓用戶輸入一個int
然後輸入這個數字的名字。用掃描器初始化的數組長度
該程序向後打印這些名稱並以相反的順序。但是,當我使用Scanner
時,存儲這些名稱的數組總是被創建爲一個元素。當我自己分配一個號碼時,我沒有這個問題。是否有與Scanner
獨特的東西或我做錯了什麼?
import java.util.Scanner;
class forTester {
public static void main (String str[]) {
Scanner scan = new Scanner(System.in);
//Why does this commented code scan only one less name than expected???
/*
System.out.println("How many names do you want to enter?");
int num = scan.nextInt();
System.out.println("Enter " + num + " Names:");
String names[] = new String[num];
*/
//Comment out the next two lines if you use the four lines above.
System.out.println("Enter " + 4 + " Names:");
String names[] = new String[4];
// The code below works fine.
for (int i = 0; i < names.length; i++) {
names[i]=scan.nextLine();
}
for(int i = names.length - 1; i >= 0; i--) {
for(int p = names[i].length() - 1; p >= 0; p--) {
System.out.print(names[i].charAt(p));
}
System.out.println("");
}
}
}