Reputation: 13
I am somewhat lost on what to do.
There are 4 parts.
Final outcome should print out as follows:
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
I've figured out everything out but can't figure out the second part. I don't exactly know how to do the code for does not contain comma.
Here's my code:
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;
}
}
Upvotes: 0
Views: 10500
Reputation: 60046
You can use :
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
}
Upvotes: 0
Reputation: 53545
Let's have a look at the line:
commaLocation = lineString.indexOf(',');
in case there is no comma, .indexOf()
returns -1
- you can take advantage of it and add an if
condition right after this line and handle this case as well!
Upvotes: 2