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

Java程序需求:按行输出单词并统计总数,修复逐字符输出问题

Fixing Your Java Word Output & Count Program

Let's break down what's going wrong with your current code and fix it to meet your goal:

Issues in Your Current Code

  • You're printing characters, not words: Your for loop iterates over each character in the input string with text.charAt(position), which is why you're getting a new line for every single character instead of each word.
  • Inaccurate word counting with split(" "): Using split(" ") will create empty string elements if there are multiple spaces, leading or trailing spaces in the input. For example, "Hello world " would split into ["Hello", "", "", "world", ""], making your word count wrong.
  • Unnecessary Integer for loop index: While using Integer isn't breaking anything here, it's more efficient and standard to use a primitive int for loop counters.

Fixed Code

public class TextTest { 
    public static void main(String[] args) { 
        do {
            String text = Input.getString("Text: "); 
            
            if (text.trim().isEmpty()) { 
                System.out.println("empty text");
                System.out.println("number of words: 0");
                continue;
            } 
            
            // Split on one or more whitespace characters (handles multiple spaces/tabs)
            String[] separated = text.trim().split("\\s+"); 
            
            // Print each word on a new line
            for (int position = 0; position < separated.length; position++) { 
                System.out.println(separated[position]); 
            } 
            
            int wordCount = separated.length; 
            System.out.println("number of words: " + wordCount); 
        } while (Repeat.repeat()); 
    }
}

Key Changes Explained

  1. Check for empty input properly: We use text.trim().isEmpty() to handle cases where the input is just spaces/tabs (which should count as empty).
  2. Better splitting logic: text.trim().split("\\s+") does two things:
    • trim() removes leading/trailing whitespace so we don't get empty strings at the start/end of the array.
    • split("\\s+") splits on one or more whitespace characters (spaces, tabs, newlines), which handles multiple spaces between words correctly.
  3. Loop through words instead of characters: Now the for loop iterates over the separated array (which holds each word) and prints each element on a new line.
  4. Standardized variable naming: Changed WordCount to wordCount to follow Java's camelCase naming convention.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:14:24