2014-02-09 117 views
0

我試圖在java中輸入字符串。我輸入應該是這樣的Java從控制檯輸入字符串輸入

3 
1,1,[email protected],123 Sesame St.,New York,NY,10011,12345689010 
1,2,[email protected],123 Sesame St.,New York,NY,10011,12345689010 
1,3,[email protected],123 Sesame St.,New York,NY,10011,12345689010 

所以,我想這

Scanner in = new Scanner(System.in); 
     int TotalNumber = in.nextInt(); 
     String[] Data = new String[TotalNumber]; 
     for (int Counter = 0; Counter < TotalNumber; Counter++) { 

      Data[Counter] = in.next(); 

     } 

     in.close(); 

     for (int counter = 0; counter < Data.length; counter++) { 


      System.out.println(Data[counter]); 

     } 

我的輸出顯示這個

1,1,[email protected],123 
Sesame 
St.,New 

什麼是我的問題嗎?如何正確輸入字符串行?

更新

,我發現我的解決方案在這裏Scanner issue when using nextLine after nextXXX

回答

1

next()處斷裂一個空白。相反,你應該使用nextLine()輸入整條生產線,以您的字符串:

int TotalNumber = in.nextInt(); 
String[] Data = new String[TotalNumber]; 
for (int Counter = 0; Counter < TotalNumber; Counter++) { 
    Data[Counter] = in.nextLine(); 
} 
+0

我嘗試nextLine()3 1,1,錯誤@ bunny.com,123芝麻街,紐約,紐約州,10011,12345689010 1,1,錯誤@ bunny.com,123 Sesame St.,紐約,紐約州,10011,12345689010它只需要我輸入2個輸入 –

+0

是否適合你? – user12458

+0

@JavaTechnical no –

0

Data[Counter] = in.nextLine();

0

什麼嘗試:

import java.util.Scanner; 
import java.lang.String; 

public class Test 
{ 
    public static void main(String[] args) 
    { 
     char[] sArray; 

     Scanner scan = new Scanner(System.in); 

     System.out.print("Enter a Palindrome : "); 
     String s = scan.nextLine(); 
     s = s.replaceAll("\\s+", ""); 

     sArray = new char[s.length()]; 

     for(int i = 0; i < s.length(); i++) 
     { 
      sArray[i] = s.charAt(i); 
      System.out.print(sArray[i]); 
     } 
    } 
} 
0

試一下這個(Mureinik修改後的代碼)..

int TotalNumber = in.nextInt(); 
in.nextLine(); 
String[] Data = new String[TotalNumber]; 
for (int Counter = 0; Counter < TotalNumber; Counter++) { 
    Data[Counter] = in.nextLine(); 
} 

您需要nextLine()服用後,因爲您將在輸入int後按回車,並在Data[0]中輸入nextLine()