如何避免char数组长度判定结果重复输出?求替代for循环方法
First, let’s clarify: you don’t need a for loop at all to get the length of a char array in Java—char arrays have a built-in length field you can access directly. The repeated output in your code comes from running those System.out.println calls inside the loop, so they execute once per iteration. Here are the best fixes:
1. Remove the For Loop Entirely (Simplest Fix)
If your only goal is to check the array length and print the corresponding rule, you don’t need a loop at all. Just access the length directly and run your conditionals once:
int fc = s.length; // Get array length once, no loop needed if (fc == 1) { System.out.println("String accepted under rule a*"); } else if (fc == 2 || fc == 4) { System.out.println("String accepted under rule a*b+"); } else if (fc >= 5) { System.out.println("String accepted under rule abb"); }
This way, each rule message will print exactly once, since we’re only running the conditionals a single time after getting the length.
2. Separate Length Check from Element Processing (If You Need to Loop Through Elements)
If you do need to iterate over the char array for other tasks (like checking individual characters), calculate the length first and run your rule check before the loop:
int fc = s.length; // Print rule once before processing elements if (fc == 1) { System.out.println("String accepted under rule a*"); } else if (fc == 2 || fc == 4) { System.out.println("String accepted under rule a*b+"); } else if (fc >= 5) { System.out.println("String accepted under rule abb"); } // Now loop through the array for other tasks (if needed) for (char c : s) { // Do something with each character, e.g., validate it System.out.println("Processing character: " + c); }
This keeps your rule output single-use while still letting you process the array elements.
3. Use Java Streams (Alternative for Modern Java)
If you prefer functional-style code (Java 8+), you can get the length via streams, though this is overkill just for length checking. But if you’re already using streams for element processing, you can get the count once:
long fc = Arrays.stream(s).count(); // Get array length as a long // Same conditional checks as before, run once if (fc == 1) { System.out.println("String accepted under rule a*"); } else if (fc == 2 || fc == 4) { System.out.println("String accepted under rule a*b+"); } else if (fc >= 5) { System.out.println("String accepted under rule abb"); } // Stream processing (if needed) Arrays.stream(s) .forEach(c -> System.out.println("Processing character: " + c));
Again, the key here is running the rule check only once, separate from any element iteration.
Quick Note on Your Original Code
In your original loop, i <= s.length will cause an ArrayIndexOutOfBoundsException because array indices go from 0 to s.length - 1. If you do need a loop, use i < s.length instead—but as we’ve covered, you don’t need a loop just to get the length.
内容的提问来源于stack exchange,提问作者Bry

