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; } }
关键修改说明
- 修正判断逻辑:把错误的字符ASCII值判断替换为
input[i].length() > 7,同时增加!input[i].isEmpty()过滤分割产生的空串,确保只统计有效且长度超7的单词。 - 优化分割规则:将
split(" ")改为split("\\s+"),可以匹配任意数量的空白字符(空格、换行、制表符等),避免因连续空格生成空串影响结果。
内容的提问来源于stack exchange,提问作者krotokys
相关产品推荐
相关产品推荐

