简体   繁体   中英

How do I split an input string in Java?

User enters a string in java, I have to split it into different components.

Scanner scanner = new Scanner(System.in);
String test = scanner.next();

// split the test variable using the split method
String [] parts = test.split(" ,", 3);

s[i].setFirstName(parts[0].trim());
s[i].setlastName(parts[1].trim());
s[i].setID(Integer.parseInt(parts[2].trim()));
s[i].setgrade(Integer.parseInt(parts[3].trim()));

but it's not working. I can only get the first word to show up.

Use nextLine() rather than next() should fix the issue.

For further reference, take a look at the docs .

With your comment

I can get only one word to show up. it doesn't read any proceeding words.

Use nextLine() instead of next() .

next() will only return what comes before a space.

nextLine() automatically moves the scanner down after returning the current line.

name = scanner.nextLine();

Scanner doc

Change

String test = scanner.next();

to

String test = scanner.nextLine();

scanner.next() takes a word upto it encounters a blank space. nextLine() will consider the whole line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM