如何在Java Scanner验证中将回车键判定为无效输入?
Hey there! I see the problem you're facing—when you just hit the enter key without typing anything, your code doesn't trigger the invalid input message. Let's break down why this happens and fix it.
Why Your Current Code Doesn't Catch Empty Entries
The Scanner.hasNextInt() method ignores leading whitespace (including newline characters from pressing enter). So when you press enter alone, the scanner just waits for non-whitespace input instead of returning false—that's why your error loop never runs in this case.
The Solution: Read Entire Lines and Validate Them
Instead of relying on hasNextInt() directly, we can read the entire input line first, check if it's empty, then try to parse it as an integer. Here's the adjusted code:
import java.util.*; public class SwitchExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int number = -1; boolean validInput = false; while (!validInput) { System.out.print("Enter ID: "); String input = scanner.nextLine().trim(); // Read full line and remove leading/trailing whitespace // Check if input is empty (only enter was pressed) if (input.isEmpty()) { System.out.println("Invalid. Enter again: "); continue; } // Try to parse the input as an integer try { number = Integer.parseInt(input); validInput = true; } catch (NumberFormatException e) { System.out.println("Invalid. Enter again: "); } } System.out.println("Your number was: " + number); System.out.println("Test message got printed!"); } }
How This Works
scanner.nextLine()reads the entire input line, including the newline character from pressing enter.trim()removes any leading/trailing whitespace (so even if someone enters spaces plus enter, it's treated as empty).- We first check if the trimmed input is empty—if yes, we show the invalid message immediately.
- If the input isn't empty, we use
Integer.parseInt()to try converting it to an integer. If that fails (e.g., non-numeric characters), theNumberFormatExceptioncatches it and we show the invalid message.
This way, both empty entries (just enter) and non-numeric inputs will trigger your error prompt, which is exactly what you want!
内容的提问来源于stack exchange,提问作者Harry

