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
forloop iterates over each character in the input string withtext.charAt(position), which is why you're getting a new line for every single character instead of each word. - Inaccurate word counting with
split(" "): Usingsplit(" ")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
Integerfor loop index: While usingIntegerisn't breaking anything here, it's more efficient and standard to use a primitiveintfor 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
- 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). - 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.
- Loop through words instead of characters: Now the
forloop iterates over theseparatedarray (which holds each word) and prints each element on a new line. - Standardized variable naming: Changed
WordCounttowordCountto follow Java's camelCase naming convention.
内容的提问来源于stack exchange,提问作者user9240778
相关产品推荐
相关产品推荐

