用户在java中输入一个字符串,我必须将其拆分为不同的组件。
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()));
但它不起作用。我只能得到第一个出现的词。
答案 0 :(得分:0)
使用nextLine()
而不是next()
来解决问题。
如需进一步参考,请查看the docs。
答案 1 :(得分:0)
发表评论
我只能得到一个词出现。它没有阅读任何程序 词语的
使用nextLine()
代替next()
。
next()
只会返回空格前的内容。
nextLine()
会自动将扫描仪向下移动。
name = scanner.nextLine();
答案 2 :(得分:0)
更改
String test = scanner.next();
到
String test = scanner.nextLine();
scanner.next()
在遇到空格时会说一句话。 nextLine()
将考虑整条线。