2013-02-21 119 views
2

我想將一個字符串拆分成一個字符串數組,但是當它拆分字符串時只有第一部分在拆分之前在[0]槽中的數組中,但沒有任何東西在[1]或以後。當它試圖拼接[1]在Java中分割一個字符串,

import java.util.Scanner; 

public class splittingString 
{ 

    static String s; 


    public static void main(String[] args) 
    { 
     Scanner input = new Scanner(System.in); 
     System.out.println("Enter the length and units with a space between them"); 
     s = input.next(); 
     String[] spliced = s.split("\\s+"); 
     System.out.println("You have entered " + spliced[0] + " in the units of" + spliced[1]); 
    } 

} 
+4

使用代碼塊一致性和邏輯縮進。代碼的縮進旨在幫助人們理解程序流程。 – 2013-02-21 16:56:53

+0

您是否驗證了輸入是您期望的內容? – aglassman 2013-02-21 16:57:52

+0

我試圖用「\\ s」和「」分割同樣的問題,如果你打印出數組的長度,它總是1 – MeryXmas 2013-02-21 16:57:54

回答

11

您應該使用輸出這也返回一個Java異常錯誤: -

input.nextLine() 

目前,使用的是接下來將返回空間delimeted

+0

這工作,謝謝。愚蠢的我。 – MeryXmas 2013-02-21 17:03:20

+0

我的榮幸,您可以在javadoc中看到其他一些方法,這些方法可以讓您讀取「拼接」結果而無需調用拆分。即input.nextDouble()和input.next() – chrisw 2013-02-21 17:06:32

5

input.next()讀取一個單詞不是整行(即將停在第一個空格處)。要閱讀整行使用input.nextLine()

3

假設您的輸入是12 34s變量的內容是12而不是12 34。您應該使用Scanner.nextLine()來讀取整行。

3

這個問題不在split()函數調用中。相反,問題出在您用來從控制檯讀取輸入的功能。

next()只會讀取您輸入的第一個單詞(基本上在它遇到的第一個空格後不會讀取)。使用nextLine()。它會讀取整行(包括空格)。

這裏更正後的代碼:

import java.util.Scanner; 

public class StringSplit { 

    static String s; 

    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 
     System.out 
       .println("Enter the length and units with a space between them"); 
     s = input.nextLine(); 
     String[] spliced = s.split("\\s+"); 
     System.out.println("You have entered " + spliced[0] 
       + " in the units of" + spliced[1]); 

    } 

} 
+1

也添加了解決方案。 – Arpit 2013-02-21 17:03:03

+0

@Arpit大聲笑我實際上是在你評論時寫的。太快了:P – Ankit 2013-02-21 17:04:37

+1

我急着在upvoting每個正確答案。並轉向下一個問題。 ;) – Arpit 2013-02-21 17:05:49