如何避免Java代码多次打印"Ascending"?代码优化求助
Fixing the Single Output Issue for Sequence Check
Got it, let's fix this issue for you! The problem with your original code is that it prints a result every time it checks a pair of numbers, which leads to repeated outputs. Plus, it has a potential array index out-of-bounds error (since you're looping up to the length of the input string instead of the split array's length). Here's the adjusted code that only prints once after verifying the entire sequence:
import java.util.Scanner; public class SequenceChecker { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Type in your order(ex.5 7 4 6 8 3 9 2 0 1 - SPACES REQUIRED): "); String input = sc.nextLine(); String[] numStrings = input.split(" "); // Convert string array to integer array for cleaner comparison int[] numbers = new int[numStrings.length]; for (int i = 0; i < numStrings.length; i++) { numbers[i] = Integer.parseInt(numStrings[i]); } boolean isAscending = true; // Check adjacent pairs, stop early if we find a non-ascending pair for (int i = 0; i < numbers.length - 1; i++) { if (numbers[i] >= numbers[i + 1]) { isAscending = false; break; // No need to check further once we know it's mixed } } // Print the final result once if (isAscending) { System.out.println("Ascending"); } else { System.out.println("Mixed"); } sc.close(); // Clean up the scanner resource } }
Key Changes Explained:
- Moved
splitoutside the loop: We only need to split the input string once to get all the numbers, instead of repeating the operation every iteration. - Added a boolean flag:
isAscendingstarts astrue, assuming the sequence is ascending until we find evidence to the contrary. - Fixed loop bounds: We loop up to
numbers.length - 1to avoid array index out-of-bounds errors (since we need to accessi+1for each pair). - Early termination: Once we find any pair where the current number is greater than or equal to the next, we set
isAscendingtofalseand break the loop immediately—no need to waste time checking the rest of the sequence. - Single final output: After verifying all necessary pairs, we print the result exactly once based on the flag's value.
Test Cases:
- Input
1 2 3 4 5 6: The loop completes without finding any non-ascending pairs, soisAscendingstaystrue—outputs "Ascending" once. - Input
1 4 2 5 2: The loop finds4 > 2on the second iteration, setsisAscendingtofalseand breaks—outputs "Mixed" once.
内容的提问来源于stack exchange,提问作者boi yeet
相关产品推荐
相关产品推荐

