如果 String 输入包含 Space 则提示错误

Prompt error if String input contains Space

我想阻止用户在 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 方法,它只接受第一个标记,在本例中为:黑色。这显然不包含space。 如果你想要整个输入,使用 nextLine()

Scanner#next() 不会 return 带有 space 的字符串,因为 space 被认为是定界符,所以对于像 black sheep

这样的输入
  • 第一次调用 next() 填充 return black
  • next() 的另一个调用将 return sheep

由于您的第二个 next() 调用的结果用作 Integer.parseInt(...) 中的参数,您得到 NumberFormatException 因为此方法无法解析 sheep.

考虑 next() 使用 nextLine() 从行中读取整个字符串。