gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 05:11:11 26 4
gpt4 key购买 nike

我想阻止用户在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com