You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java使用substring方法查找字符串变量中特定字符失败问题求助

问题根因分析
  • 核心逻辑错误:循环的else分支设置了break,只要当前遍历的字符不是.就会直接终止循环,仅当字符串第一个字符是.时才能触发校验,后续所有字符都不会被检查。比如输入字符串为test.name,原代码检查第一个字符t不是.,直接跳出循环,完全不会检测到中间的.,这是不符合预期的最主要原因。
  • 逻辑遗漏:即便触发了.的校验规则,完成用户交互后没有终止循环,后续还会继续遍历剩余字符,可能重复弹出错误提示。
  • 方法使用冗余:取单个字符使用substring(x, x+1)是可行的,但用charAt(x)性能更优、代码更简洁。
修复方案
  1. 删除else分支的break语句,保证循环可以遍历字符串所有字符
  2. 检测到.并完成用户交互后,主动终止循环,避免重复执行
  3. 可选优化:将substring替换为charAt简化代码,把字符检测和用户交互逻辑拆分,提升可读性
修正后代码示例
System.out.println("\nEnter name: ");
String name = in.nextLine();
int length = name.length();
boolean hasDot = false;

// 遍历所有字符检查是否存在点号
for (int x = 0; x < length; x++) {
    if(name.charAt(x) == '.') {
        hasDot = true;
        break; // 找到点号后直接终止遍历
    }
}

// 统一处理错误逻辑
if (hasDot) {
    System.out.println("Error! - name cannot contain (.) values\n"
                     + "***************************************************");
    System.out.println("\nWould you like to capture another name?" +
    "\nEnter (1) to continue or any other key to exit");
    String opt1 = in.nextLine();
    if (opt1.equals("1")) {
        System.out.println("menu launch");
    } else {
        System.exit(0);
    }
}

内容的提问来源于stack exchange,提问作者Brad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 01:54:04