Question

I need to get from the keyboard in just one line something like this:

create 1000 John 4000  

(for a cinema program, that include the function to create users)

Where "create" is a command for create a new user (create is a class, and it contains the client information), "1000" is the ID of the user (int), "john" his name(string), and "4000" his points(int)

How can I get this different data types in one line to be stored in the different attributes for client?

Was it helpful?

Solution

I would use a Scanner object based on System.in to read the line in, using if (myScanner.hasNextLine()) and myScanner.nextLine() method pairs.

Then the line would need to be parsed, and here I'd offer you two possible ways:

  • Consider using a new Scanner based on the line just read in, say into a String variable called line, a "line Scanner" so to speak, Scanner lineScanner = new Scanner(line), and get your tokens via lineScanner.next(), lineScanner.nextInt(), lineScanner.next(), and lineScanner.nextInt(), in that order. Don't forget to close() the lineScanner when done using it.
  • Or use String#split(" ") to split the String into an array of the four subStrings that were separated by the space.

Then in the for loop where you parse the line, create any object needed based on the data obtained.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top