Noah Iarrobino
Noah Iarrobino

Reputation: 1553

Formatting entered stream data in java

I am curious how to get input data formatted from a user in java, for example if the user enters 1,2,3 how can I get these numbers in an array when the input look like this:

Scanner s = new Scanner(); String inputString = s.nextLine();

I can get a single number Integer num = Integer.parseInt(inputString) but I am unsure how handling multiple numbers would go

Upvotes: 0

Views: 95

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 103273

Well, you'd use... scanner. That's what it is for. However, out of the box a scanner assumes all inputs are separated by spaces. In your case, input is separated by a comma followed by/preceded by zero or more spaces.

You need to tell scanner this:

Scanner s = new Scanner(System.in);
s.useDelimiter("\\s*,\\s*");
s.nextInt(); // 1
s.nextInt(); // 2
s.nextInt(); // 3

The "\\s*,\\s*" think is a regexp; a bit of a weird concept. That's regexpese for 'any amount of spaces (even none), then a comma, then any amount of spaces'.

You could just use ", " too, that'll work, as long as your input looks precisely like that.

More generally if you have a fairly simple string you can use someString.split("\\s*,\\s*") - regexes are used here too. This returns a string array with everything between the commas:

String[] elems = "1, 2, 3".split("\\s*,\\s*");
for (String elem : elems) {
    System.out.println(Integer.parseInt(elem));
}
> 1
> 2
> 3

Upvotes: 1

Related Questions