2013-03-24 2 views
1

나는이 코드를 가지고 있으며 사용자가 다음 입력을 기다릴 때 처음 건너 뛴 얼굴을 제외하고는 모든 것이 실행되고 있습니다. 여기 코드는 다음과 같습니다for 루프 건너 뛰기 문제

여기
import java.util.Scanner; 
public class mainThread { 
    public static int size; 
    public static int counter; 
    public static Scanner input = new Scanner(System.in); 
    public static String currentIn; 
    public static void main(String[] args){ 
     System.out.println("Please type the desired amount of players: "); 
     size = input.nextInt(); 
     String nameArray[] = new String[size]; 
     for(int counter = 0; counter < size; counter++){ 
      System.out.println("Please enter the name of player " + (counter+1)); 
      currentIn = input.nextLine(); 
      nameArray[counter] = currentIn; 
      System.out.println(nameArray[counter]); 
     } 
    } 
} 

콘솔의 말씀입니다 :

Please type the desired amount of players: 
3 
Please enter the name of player 1 

Please enter the name of player 2 
Jacob 
Jacob 
Please enter the name of player 3 

그것은 완전히 처음 루프를 건너 뛰고 난 이유를 알아낼 수 없습니다. 시간 내 줘서 고마워!

+0

'nextInt()'만이 in 값을 읽으며 나머지는 읽지 않습니다. 'input.nextLine();'을 추가하여 나머지 라인을 무시할 수 있습니다. –

답변

0

잘 모르겠어요 무엇을 문제는,하지만 당신은 함께 라인

currentIn = input.nextLine(); 

을 교체하는 경우 :

currentIn = input.next(); 

작동합니다. 당신이 입력 (3)을 제공하고이 버퍼에 유지하고 새로운 라인 값으로 계산 입력, Enter 키를 누르면

+0

당신이 도와 줬어. –

+0

그 점을 제외하고는 플레이어 이름에 공백이 포함될 수 없으므로 이상적인 것으로 들립니다. –

1

nextInt()은 "3"을 읽지 만 줄 바꿈 부분은 읽지 않습니다. 그것은 기본적으로 첫 번째 토큰 구분자까지 읽는 것이지만 그것을 소비하지는 않습니다. 당신이 다음

3 Foo 

히트 수익을 입력한다면, 그것은 첫번째 선수의 이름으로 "푸"걸릴 것이다. 당신은 아마 선수의 수를 찾을 때 nextLine()를 사용하려면 같은

는 너무 소리 : 개인적으로 나는 항상이 같은 조금 성가신 것으로 Scanner을 발견했습니다

String playerCountText = input.readLine(); 
size = Integer.parseInt(playerCountText); // Or use a NumberFormat 

- 그것은 일종의 만들 것을 약속드립니다 모든 것을 간단하지만 정말

+0

알맞은 감사합니다! –

+0

Jon,'input.readLine().trim()'-'3 '와 같은 잘못된 입력은 NumberFormatException이 될 것입니다. –

+0

@Aniket : 물론, 자르거나 잘못된 것으로 간주해야합니다. 숫자가 아니거나 부정적이기 때문에 사용자가 입력 한 내용이 항상 유효하지 않을 수 있습니다. –

1

은 그래서 프로그램을 수정 ... 할 것 모든 것을 해결해야

import java.util.Scanner; 
public class mainThread { 
    public static int size; 
    public static int counter; 
    public static Scanner input = new Scanner(System.in); 
    public static String currentIn; 
    public static void main(String[] args){ 
     System.out.println("Please type the desired amount of players: "); 
     size = Integer.parseInt(input.nextLine().trim()); 
     String nameArray[] = new String[size]; 
     for(int counter = 0; counter < size; counter++){ 
      System.out.println("Please enter the name of player " + (counter+1)); 
      currentIn = input.nextLine(); 
      nameArray[counter] = currentIn; 
      System.out.println(nameArray[counter]); 
     } 
    } 
} 

문제는 있습니다 .. \n가 버퍼에 남아와 .nextLine()이 생략 된 이유 즉이었다

편집, 일부 입력 검증을 완료 한 다음 프로그램 :

import java.util.Scanner; 
public class mainThread { 
    public static int size; 
    public static int counter; 
    public static Scanner input = new Scanner(System.in); 
    public static String currentIn; 
    public static void main(String[] args){ 
     boolean valid = false; 
     System.out.println("Please type the desired amount of players: "); 
     while(valid == false){ 
     try{ 
      size = Integer.parseInt(input.nextLine().trim()); 
      valid = true; 
     }catch(Exception e){ 
      System.out.println("Error input, try again"); 
     } 
     } 
     String nameArray[] = new String[size]; 
     for(int counter = 0; counter < size; counter++){ 
      System.out.println("Please enter the name of player " + (counter+1)); 
      currentIn = input.nextLine(); 
      nameArray[counter] = currentIn; 
      System.out.println(nameArray[counter]); 
     } 
    } 
} 
0

은 기본적으로 일이 당신은 루프

currentIn = 입력 내부에 새로운 라인을 읽을 때 .nextLine();

처음으로 저장된 새 줄을 입력으로 사용합니다. 을 추가하여이를 피할 수 있습니다. currentIn = input.nextLine(); 이후 크기 = input.nextInt();

또는 입력을 파일에서 읽는 것.