我有代码,用户输入一个字符串,我需要在多个单词的中间删除空格。
这就是我所拥有的:
`System.out.println("Enter your choice:\n"
+ "Type 'Player Name' to search for a player based off their name.\n"
+ "Type 'Player School' to search for a player based off their school\n"
+ "Type 'Team Location' to search for a team based off their location.\n"
+ "Type 'Team Mascot' to search for a team based off their mascot.\n");
String choice = input.next();
choice = choice.replaceAll("\\s+", "");
System.out.println(choice);
switch(choice.toLowerCase()){
case "playername":
searchPlayer();
break;
case "playerschool":
searchSchool();
break;
case "teamlocation":
searchLocation();
break;
case "teammascot":
searchMascot();
break;
default:
System.out.println("Yet to be implemented");
break;
}`
这给了我没有错误,但是当我包含空格时它总是返回默认情况。 我把线条打印出选择,看看为什么它不起作用,当我运行它时它只保留第一个字。 例如,如果我输入"播放器名称"它将返回"播放器"。
答案 0 :(得分:2)
使用input.nextLine()
更改input.next()
以考虑整行输入。 input.next()
将输入保存到分隔符的位置,默认情况下是一个或多个空格。