Reputation: 1225
I want to be able to distinguish the user's input using spaces, where each string they input in one line is used for something different.
Specifically, each word they input is used in a method where I add an item to a list. The user will type 'add' followed by the item's type and age.
I have just messed around trying to figure something out but I am just lost.
if (input.equals("add")) {
scan.next(); ??
}
After the user types 'add', they then input a type and age for a vehicle that they want to add to a list. For example, 'car 7' may be typed so a new item in a list can be made, and 'car' will be its type and '7' will be its age.
To note: age is an int.
Upvotes: 1
Views: 68
Reputation: 40024
You can also read them one at a time as well as change the delimiter. Here are several examples.
String text = "The quick brown fox jumped over the lazy dog";
Scanner scan = new Scanner(text);
while (scan.hasNext()) {
System.out.print(scan.next() + " ");
}
System.out.println();
And this one changes the delimiter between words. You can specify a regular expression pattern
or a simple String
.
text = "The:quick,+-brown::::fox:.:jumped++over,,,,the,+,+lazy---dog";
scan = new Scanner(text);
// regular expression delimiter. Any combo of one or more of the chars.
scan.useDelimiter("[:,.;+-]+");
while (scan.hasNext()) {
System.out.print(scan.next() + " ");
}
System.out.println();
Upvotes: 0
Reputation: 15423
If the user enters:
car 7
all you need to do to read that line is:
String words[] = scan.nextLine().split(" ");
Now you have an array that contains the words of that line. For eg: words[0]
would contain car, words[1]
would contain 7, etc.
Upvotes: 2