0

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"))
Shajinator
  • 25
  • 5

5 Answers5

1

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.

InfoSponge
  • 104
  • 1
  • 3
0

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);
Wyatt Lowery
  • 513
  • 1
  • 7
  • 21
0

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.

RamanSB
  • 1,162
  • 9
  • 26
  • 1
    Keep in mind that this is not creating a list of items, as the @op required. It is merely replacing the comma character with newline, which has the same visual result, but not the same flexibility. – Paul92 Sep 15 '15 at 22:44
  • @Paul92 Thanks I have taken the above in to consideration and made appropriate modifications. – RamanSB Sep 15 '15 at 22:48
  • And what if he enters: "dog, cat, gila monster, iguana"? You'd remove the space in 'gila monster'. – Kylar Sep 15 '15 at 22:59
  • @Kylar it would be ideal for the user to use a hyphen, nevertheless I have mad edits to accommodate such input. – RamanSB Sep 15 '15 at 23:09
0

String[] orderArray = response.split(',');

is the way to go. As mentioned by others. Also try to use equalsIgnoreCase when getting yes/no from user.

DhruvG
  • 394
  • 1
  • 2
  • 10
0

Another way to avoid trailing and preceding whitespace when splitting, use response.split(\\s*,\\s*);.

hyper-neutrino
  • 5,272
  • 2
  • 29
  • 50