我有点迷失了该怎么做。
共有4个部分。
最终结果应打印如下:
Enter input string: Jill, Allen
First word: Jill
Second word: Allen
Enter input string: Golden , Monkey
First word: Golden
Second word: Monkey
Enter input string: Washington,DC
First word: Washington
Second word: DC
Enter input string: q
我已经弄清楚了所有事情,但无法弄清楚第二部分。我不知道怎么做代码不包含逗号。
这是我的代码:
import java.util.Scanner;
public class ParseStrings {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String lineString = "";
int commaLocation = 0;
String firstWord = "";
String secondWord = "";
boolean inputDone = false;
while (!inputDone) {
System.out.println("Enter input string: ");
lineString = scnr.nextLine();
if (lineString.equals("q")) {
inputDone = true;
}
else {
commaLocation = lineString.indexOf(',');
firstWord = lineString.substring(0, commaLocation);
secondWord = lineString.substring(commaLocation + 1, lineString.length());
System.out.println("First word: " + firstWord);
System.out.println("Second word:" + secondWord);
System.out.println();
System.out.println();
}
}
return;
}
}
答案 0 :(得分:1)
让我们来看看这一行:
commaLocation = lineString.indexOf(',');
如果没有逗号,.indexOf()
会返回-1
- 您可以利用它并在此行之后添加if
条件并处理此案例!
答案 1 :(得分:0)
您可以使用:
if (input.matches("[^,]+,[^,]+")) {//If the input match two strings separated by a comma
//split using this regex \s*,\s* zero or more spaces separated by comman
String[] results = input.split("\\s*,\\s*");
System.out.println("First word: " + results[0]);
System.out.println("Second word: " + results[1]);
} else {
//error, there are no two strings separated by a comma
}