2014-10-29 53 views
0

我想讓用戶輸入一個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(""); 
     } 
    } 
} 

回答

0

更改註釋代碼:

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]; 
    scan.nextLine(); // added this to consume the end of the line that contained 
        // the first number you read 
0

的問題是,這將是由nextLine()在第一次迭代被吞併新的行字符後面nextInt()葉。所以,你覺得數組的大小要少一個。實際上,數組的第一個元素,即第0個索引將具有新的行字符。

你的代碼應該是:

System.out.println("How many names do you want to enter?"); 
    int num = scan.nextInt(); // leaves behind a new line character 
    System.out.println("Enter " + num + " Names:"); 
    String names[] = new String[num]; 
    scan.nextLine() // to read the new line character left behind by scan.nextInt()