2012-01-15 15 views
1

問題は、空白をすべて空白に分割しようとすると、変数inputを次の()で読み込むことができないということです。私はkeyboard.nextLine()を使用しなければならなかったので、分割プロセスは動作するはずです。配列のすべての単語を取得しますが、問題は次のようになります。nextLine()を使用すると、最初の変数(答え)を読んで、それは私がそれはここで働いて作ることができる唯一の方法ですコード文字列の読み込みnext()とnextLine()Java

Scanner keyboard=new Scanner(System.in); 
    Scanner keyboard2=new Scanner(System.in);//just to make answer word 

    int answer=keyboard.nextInt();//if I don't use the keyboard2 here then the program will not work as it should work, but if I use next() instead of nextLine down there this will not be a problem but then the splitting part is a problem(this variable counts number of lines the program will have). 

    int current=1; 
    int left=0,right=0,forward=0,back=0; 

    for(int count=0;count<answer;count++,current++) 
    { 
     String input=keyboard.nextLine(); 
     String array[]=input.split(" "); 
     for (int counter=0;counter<array.length;counter++) 
     { 
      if (array[counter].equalsIgnoreCase("left")) 
      { 
       left++; 
      } 
      else if (array[counter].equalsIgnoreCase("right")) 
      {  
       right++; 
      } 
      else if (array[counter].equalsIgnoreCase("forward")) 
      { 
       forward++; 
      } 
      else if (array[counter].equalsIgnoreCase("back")) 
      {  
       back++; 
      } 
     } 

    } 
} 

感謝:)

+1

句読点を含めるように質問を編集してください。あなたの質問が何であるかを理解することは本当に難しいです。 –

答えて

11

は、この行の後keyboard.nextLine()を置きます:

int answer=keyboard.nextInt(); 

これは、あなたがScannerクラスのnextInt()方法後nextLine()メソッドを使用する際に通常起こる共通の問題です。

実際には、ユーザがint answer = keyboard.nextInt();に整数を入力すると、スキャナは数字だけを受け取り、改行文字\nを残します。したがって、改行文字を破棄するにはkeyboard.nextLine();に電話してください。その後、String input = keyboard.nextLine();を問題なく呼び出すことができます。

関連する問題