So I'm trying to write a program where it reads in parts of a string per each line. For example the user can input:
Item car small
Item toy big
which com开发者_JS百科es across as this:
Item <item name> <size>
Basically, with this information, I store it into the program, so that whenever the user whats to access it later they can call it. The first string car
indicates to the program, that the user is storing another item into the database. My question is, how do I read the input so that I can grab each section of the string item
<item name>
and <size>
.
You can use the split
method:
Scanner scan = new Scanner(System.in);
String wholeLine = scan.nextLine();
String[] tokens = whileLine.split();
now token[0]
should be "Item"
, token[1]
should be "car"
and token[2]
should be "small"
, if the user inputs Item car small
for(Scanner sc = new Scanner(new File("my-input-file.txt")); sc.hasNext(); ) {
String[] words = sc.nextLine().split(" ");
String itemName = words[1];
String size = words[2];
// Now store itemName, size in the DB...
}
Read a each line with readLine() method and then use StringTokenizer to get tokens out of it.
精彩评论