java.util.scanner - Read a character followed by n number of integers like A 1 2 3 using Java's Scanner(System.in) object from the same line -
i unable read 1 2 3 same line, 1 2 3 can read 1 line because of in start, scanner reads a.
string command = ""; int numbers; list<integer> ints = new arraylist<integer>(); scanner scan = new scanner(system.in); command = scan.next(); while (scan.hasnextint()) { numbers = scan.nextint(); ints.add(numbers); } scan.close();
i use nextline()
(and hasnextline()
), split on 1 or more consecutive white-space characters (to create array of tokens), set command
first token , stream
tokens - skip first 1 (it's command
) , collect list
. like,
scanner scan = new scanner(system.in); while (scan.hasnextline()) { string line = scan.nextline(); string[] tokens = line.split("\\s+"); string command = tokens[0]; list<integer> ints = stream.of(tokens).skip(1) .maptoint(integer::parseint).boxed().collect(collectors.tolist()); system.out.printf("command = %s, ints = %s%n", command, ints.tostring()); }
Comments
Post a Comment