我想阻止用户在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:
UPDATE:
尝试使用.nextLine()
而不是.next()
。但是,仍然收到错误输出:
Name of Team 1: black sheep
Error
Error
[] Goals: [] Goals:
放置[]
取代原来Space
/empty
输出
谢谢我将代码更改为.nextLine()而不是.next()。这一次发生了不同的情况。它没有考虑到我对Space的投入,它仍然跳转到下一张图片 – gymcode 2015-02-09 12:37:54
与我的好朋友Google找到这些信息有些麻烦。 “next()”的默认分隔符只是一个空格吗? – 2015-02-09 12:41:32
我怀疑你在nextLine()之前使用了'nextInt()'或其他形式的'nextXXX()'方法。你可以在这里找到这个问题的解决方案http:// stackoverflow。com/questions/13102045/skip-nextline-after-use-nextint – Pshemo 2015-02-09 12:42:04