Reputation: 25
If the user types yes, I am trying to create a list(receipt) of everything the user entered between the commas. For example: cat, dog, fish would return: cat dog fish on separate lines. Would I use indexOf?
if (language.equals("English")) System.out.println("Please enter your order here (using commas to separate choices!)");
String order =kboard.nextLine();
if (language.equals("English")) System.out.println("Would you like a reciept (yes/no)?");
String response =kboard.nextLine();
if (response.equals("yes"))
Upvotes: 0
Views: 81
Reputation: 5425
Another way to avoid trailing and preceding whitespace when splitting, use response.split(\\s*,\\s*);
.
Upvotes: 0
Reputation: 414
String[] orderArray = response.split(',');
is the way to go. As mentioned by others. Also try to use equalsIgnoreCase when getting yes/no from user.
Upvotes: 0
Reputation: 1172
You can use the replaceAll method on Strings.
Say the user enters: "dog, cat, mouse, pussy-cat,"
String response = "dog, cat, mouse, pussy-cat,"
//The above line will remove any blank spaces.
String[] userInput = response.split(", ");
This will create an array of Strings each index contains the words inputted by the user, in respective order.
Upvotes: 0
Reputation: 513
Use the split(parser)
method. Instead of making the input just one string, use an array. For your case, use the following code.
String[] order = kboard.nextLine().split(", ");
Alternatively, you could do split(",");
and then use the trim()
method to remove any extra white space. (You never know how much might be there)
The split()
method will return an array of strings, which you can now use. So if you wanted to print it out, do something like this:
for(String s: order)
System.out.println(s);
Upvotes: 0
Reputation: 114
If your source string is going to be a comma separated list like this, "cat, dog, bug", and you're using java, than I would String.split and set the delimiter to be a ','.
This will return an array of Strings you can then play with like so:
String textToParse = "cat, dog, bug";
String[] tokens = textToParse.split(',');
You could also use a regular expression but that seems like overkill to me.
Upvotes: 1