2014-10-29 4 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() 잎. 따라서 배열 크기가 1보다 작다고 느낍니다. 사실, 배열의 첫 번째 요소, 즉 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() 
관련 문제