2016-04-23 43 views
0

我很難將用戶輸入的字符串拆分爲兩個單詞。該字符串格式爲「word1,word2」,我正在嘗試創建兩個單獨的字符串word1和word2。這裏是我的嘗試:將逗號和空格分隔的輸入拆分爲兩個單詞

System.out.println("Enter the two words separated by a comma, or 'quit':"); 

Scanner sc = new Scanner(System.in); 

String input = sc.next(); 

while(!input.equals("quit")){ 
    input.replaceAll("\\s+",""); 

    System.out.println(input); //testing 

    int index1 = input.indexOf(","); 

    String wordOne = input.substring(0, index1); 

    String wordTwo = input.substring(index1+1, input.length()); 

    if(wordOne.length()!=wordTwo.length()){ 
      System.out.println("Sorry, word lengths must match."); 
     } 

    System.out.println("Enter the two words separated by a comma, or 'quit':"); 

    input = sc.next(); 
} 

這是輸出:

Enter the two words separated by a comma, or 'quit': 
leads, golds 
leads, 
Sorry, word lengths must match. 
Enter the two words separated by a comma, or 'quit': 
golds 
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 
    at java.lang.String.substring(String.java:1911) 
    at Solver.main(Solver.java:22) //this points to the line "String wordOne = input.substring(0, index1);" 

可能有人請告訴我,我錯了?

+0

將結果返回給輸入input = input。replaceAll(「\\ s +」,「」);' –

回答

0

問題是,您正在使用sc.next()而不是sc.nextLine()。我可以看到,在您的輸入中,您正在輸入「線索,黃金」,然後是空格。在這種情況下,sc.next()將返回「引線」,而不是「鉛,黃金」

1

你爲什麼不嘗試:

input.split(","); 

這會給你一個字符串數組。來自JavaDocs。

public String[] split(String regex) 

拆分這串繞定正則表達式的匹配。 此方法的工作原理與通過使用 給定表達式和零極限參數調用雙參數拆分方法相同。尾隨空的 字符串因此不包含在結果數組中。

更新:,因爲你正在使用sc.next(),除非它認爲其將會終止輸入一個空格,這將需要一個字。您應該使用sc.nextLine()來保留完整的輸入作爲用戶輸入。

next()

public java.lang.String next() 查找並返回來自此掃描器的下一個完整的 令牌。一個完整的令牌前後是 輸入,它與分隔符模式匹配。即使先前調用hasNext 返回true,此方法可能會阻止 等待要掃描的輸入。

nextLine()

public java.lang.String nextLine()

此掃描器的 當前行,並返回跳過的輸入信息。此方法 返回當前行的其餘部分,排除 末尾的任何行分隔符。該位置設置爲下一行的開頭。由於 此方法繼續搜索輸入查找行 分隔符,它可能會將搜索該行的所有輸入緩衝到 如果沒有行分隔符存在,則跳過。

+0

他正在得到一個異常,他需要幫助解決這個問題。而這個例外並不是因爲他試圖用空格替換逗號,而是因爲他沒有閱讀整個輸入,而是閱讀部分內容。 – Madhusudhan

+0

@ user3493289因爲他試圖實現手動算法,而不是已經開發和提供的字符串 – 2016-04-23 08:53:36

+0

但您的解決方案並不能解決他正在獲取的異常。例外是因爲使用sc.next()而不是sc.nextLine()。他的算法的改進應該是一個評論而不是一個答案。 – Madhusudhan