Java数组输入方法无响应问题排查及移除数组中7的功能实现求助
Why Your Input Method Isn't Responding
The problem with your userInput() method is that Scanner.hasNextInt() is a blocking call — it will keep waiting indefinitely for more integer input until you signal the end of input. On most systems, you can do this by pressing:
Ctrl + D(Linux/macOS)Ctrl + Z(Windows, then press Enter)
Without this signal, the program sits there waiting for you to keep entering numbers, making it look unresponsive. Let's tweak the method to add a user-friendly prompt so you know how to finish inputting.
Improved Input Method
Here's an updated version with clear instructions for the user:
import java.util.Arrays; import java.util.Scanner; public class RemoveSevens { static Scanner in = new Scanner(System.in); public static int[] userInput() { int[] inputs = new int[5]; int currentSize = 0; System.out.println("Enter integers (type a non-integer or press Ctrl+D/Ctrl+Z to finish):"); while (in.hasNextInt()) { // Resize array if we're running out of space if (currentSize == inputs.length) { inputs = Arrays.copyOf(inputs, 2 * inputs.length); } inputs[currentSize] = in.nextInt(); currentSize++; } // Trim the array to the actual number of elements entered inputs = Arrays.copyOf(inputs, currentSize); return inputs; }
Implementing the Remove-7 Logic
Now let's add the function that removes all 7s, shifts remaining elements left, and fills empty spots with 0s:
public static int[] removeSevens(int[] arr) { int nonSevenCount = 0; // First count how many elements aren't 7 for (int num : arr) { if (num != 7) { nonSevenCount++; } } // Create a result array (original array length is preserved) int[] result = new int[arr.length]; int index = 0; // Copy non-7 elements to the front for (int num : arr) { if (num != 7) { result[index++] = num; } } // Remaining positions are already 0 by default in Java, no extra work needed return result; }
Putting It All Together with a Main Method
Add a main method to test everything end-to-end:
public static void main(String[] args) { int[] inputArray = userInput(); int[] processedArray = removeSevens(inputArray); System.out.println("Original array:"); printArray(inputArray); System.out.println("\nArray with all 7s removed and gaps filled with 0:"); printArray(processedArray); } // Helper method to print arrays neatly public static void printArray(int[] arr) { System.out.print("["); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]); if (i != arr.length - 1) { System.out.print(", "); } } System.out.println("]"); } }
How to Test It
- Run the program — it will prompt you to enter integers.
- Type in numbers like
7 2 7 5 3and then press Ctrl+D/Ctrl+Z to end input. - You'll see the original array and the processed array with 7s removed, and the end filled with 0s.
For example, if you input 7 2 7 5 3, the processed array will be [2, 5, 3, 0, 0].
内容的提问来源于stack exchange,提问作者Antonia Farina

