我想阻止用户在 String
输入中包含 Space
。
我尝试过使用一些方法,例如:
(team1Name.contains(""))
(team1Name.matches(".*([\t]).*"))
(team1Name.indexOf(' ') >= 0)
但无济于事。
下面是我的代码片段和输出:
代码片段:
System.out.print("Name of Team 1: ");
team1Name = sc.next();
if (team1Name.indexOf(' ') >= 0) {
System.err.println("Error");
System.out.print("Name of Team 1: ");
team1Name = sc.next();
}
System.out.print(team1Name+ " Goals: ");
while (true) {
try {
team1Goals = Integer.parseInt(sc.next());
break;
} catch (NumberFormatException nfe) {
System.err.println("Error");
System.out.print(team1Name+ " Goals: ");
}
}
输出:
Name of Team 1: black sheep
Error
black Goals: black Goals:
更新:
尝试使用 .nextLine()
而不是 .next()
。但是,仍然收到错误输出:
Name of Team 1: black sheep
Error
Error
[] Goals: [] Goals:
放置[]
替换原来的Space
/empty
输出
最佳答案
Scanner#next()
不会返回带空格的字符串,因为空格被视为分隔符,所以对于像 black sheep
- 第一次调用
next()
填充返回black
- 和
next()
的另一个调用将返回sheep
。
由于您第二次 next()
调用的结果用作 Integer.parseInt(...)
中的参数,您将得到 NumberFormatException
因为这个方法不能解析sheep
。
考虑使用 nextLine()
代替 next()
从行中读取整个字符串。
关于java - 如果 String 输入包含 Space 则提示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28409563/