2012-01-15 80 views
1

問題是我無法用next()讀取變量輸入,當我嘗試拆分(.split「」)每個空白,然後數組只是得到前兩個單詞I鍵入所以我不得不使用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

請問您可以編輯您的問題以包含標點符號。真的很難理解你的問題是什麼。 – 2012-01-15 21:12:47

回答

11

keyboard.nextLine()此行之後:

int answer=keyboard.nextInt(); 

這是當你後ScannernextInt()方法使用nextLine()方法通常發生的常見問題。

實際情況是當用戶在int answer = keyboard.nextInt();處輸入一個整數時,掃描器將只取數字並留下換行符\n。所以你需要通過調用keyboard.nextLine();來唬住這個新行字符,然後你可以打電話String input = keyboard.nextLine();沒有任何問題。