2014-12-29 5 views
0

내 전체 코드는 아래에 게시됩니다. 내 문제는이 출력에서 ​​볼 수 있습니다 :For 루프를 사용하여 Java에서 사용자 입력을받는 방법?

위에서 볼 수 있듯이 for 루프의 첫 번째 반복은 사용자 입력없이 실행됩니다. 마치 건너 뛴 것처럼 보입니다.

내 질문은 루프의 각 반복마다 사용자 입력을 요청하는 For 루프를 어떻게 만듭니 까? 내 코드가 지금하고있는 것처럼 반복을 건너 뛰지 않습니다. 나는 인터넷에서 온갖 해답을 찾았지만 특별히 찾아 낼 수는 없다. 여기

import java.util.Scanner; 
import java.util.ArrayList; 

class read { 
    public static void main(String[] args) { 

     // Create instance of class 
     Tape instructions = new Tape(); 


     // Assign scanner to keyboard variable 
     Scanner keyboard = new Scanner(System.in); 


     // Get user input for mConfig and convert to char 
     System.out.print("Enter the character representation of your first configuration: "); 
     String userMConfig = keyboard.nextLine(); 
     char c = userMConfig.charAt(0); 


     // Get number of symbols/operations/f-configurations 
     System.out.print("How many symbols are under this configuration? "); 
     int numOfSymbols = keyboard.nextInt(); 


     // Define array of symbols 
     ArrayList<String> userSymbols = new ArrayList<String>(); 

     for (int i = 1; i<= numOfSymbols; i++) 
     { 
      System.out.println("Enter the first symbol: "); 
      String userInputSymbol = keyboard.nextLine(); 
      userSymbols.add(userInputSymbol); 

     } 



     // Assign values to object methods 
     instructions.mConfig(c); 
     instructions.symbols(userSymbols); 



     // Testing code 
     System.out.println(instructions.getSymbols()); 





    } 
} 

는 단지 내 For 루프 :이

int numOfSymbols = keyboard.nextInt(); 

을 수행 할 때 스캐너가 사용자의 입력 라인의 정수 부분이 필요하지만 버퍼에 '\n'

for (int i = 1; i<= numOfSymbols; i++) 
      { 
       System.out.println("Enter the first symbol: "); 
       String userInputSymbol = keyboard.nextLine(); 
       userSymbols.add(userInputSymbol); 

      } 

답변

2

. 당신이 당신의 루프의 첫 번째 반복에서

String userInputSymbol = keyboard.nextLine(); 

를 호출 할 때 이유 '\n' 빈 라인을 생산, 즉시 반환됩니다 있다는 것입니다. 당신이 keyboard.nextLine()이 정수를 읽기 위해 수동으로 int를 분석 한 다음 사용할 수,

int numOfSymbols = keyboard.nextInt(); 
keyboard.nextLine(); // Throw away the '\n' from the line that contained int 

을 다른 방법 :

바로 numOfSymbols을 읽은 후 keyboard.nextLine();를 추가,이 문제를 해결하려면.

일반적으로 nextLineScanner의 다른 호출과 혼합하는 경우에는 후행 '\n' 문자의 문제로 인해주의해야합니다.

1

nextInt()은 줄 끝 문자를 사용하지 않기 때문에 발생합니다.

무엇을 할 수 있습니까? 당신은 nextInt() 전화 후 수동으로 소비 할 수 있습니다 : 당신이 더 많은 정보를 원하는 경우 this post을 참조 할 수 있습니다

int numOfSymbols = keyboard.nextInt(); 
... 
keyboard.nextLine(); // Consume the end-of-line character 

for (int i = 1; i <= numOfSymbols; i++) { 
    ... 
} 

.

2

여기서 문제는 nextInt()이 int를 읽고 줄 바꿈 문자를 스트림에 남겨 둡니다. 그런 다음 nextLine()을 호출하면이 문자를 읽고 빈 문자열을 반환합니다. 이를 피하려면 다음을 사용하십시오.

int numOfSymbols = keyboard.nextInt(); 

keyboard.nextLine(); // this will swallow the "\n" 

// Now your for loop should work fine 
for (int i = 0; i < numOfSymbols; i++) 
{ 
    System.out.println("Enter the first symbol: "); 
    String userInputSymbol = keyboard.nextLine(); 
    userSymbols.add(userInputSymbol); 
} 
관련 문제