我很難將用戶輸入的字符串拆分爲兩個單詞。該字符串格式爲「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);"
可能有人請告訴我,我錯了?
將結果返回給輸入input = input。replaceAll(「\\ s +」,「」);' –