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

Java程序逻辑异常:无法输出长度超7的单词,始终显示no words

问题分析与修复方案

核心错误点

原代码的判断逻辑完全偏离需求:

  • 代码中input[i].charAt(0) <=7是在比较单词首字符的ASCII值是否小于等于7(对应不可见控制字符),完全没有对单词长度进行判断,导致符合长度要求的单词根本不会被计数,最终错误输出no words。
  • 额外隐患:用split(" ")分割输入时,如果输入有连续空格,会生成空字符串,可能导致无意义的判断。

修复后的完整代码

package example_1;
import java.util.Scanner;

public class lab9{
    public static void main(String[] args) {
        String[] input = Scan().split("\\s+");
        int words = 0;
        
        for(int i=0; i < input.length;i++) {
            if(!input[i].isEmpty() && input[i].length() > 7) {
                System.out.print(input[i] + ' ');
                words++;
            }
        }
        if (words == 0) {
            System.out.print("no words");
        }
    }
    public static String Scan() {
        String word;
        Scanner scn = new Scanner(System.in);
        System.out.print("input= ");
        word = scn.nextLine();
        scn.close();
        return word;
    }
}

关键修改说明

  1. 修正判断逻辑:把错误的字符ASCII值判断替换为input[i].length() > 7,同时增加!input[i].isEmpty()过滤分割产生的空串,确保只统计有效且长度超7的单词。
  2. 优化分割规则:将split(" ")改为split("\\s+"),可以匹配任意数量的空白字符(空格、换行、制表符等),避免因连续空格生成空串影响结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 17:20:31