Java简易程序无法获取输入的技术求助
解决Java程序无法获取输入的问题
Hey, let's fix that input issue in your Java code right away! The root problem here is that you're creating multiple Scanner instances to read from System.in—this messes up the input stream buffer and causes your program to hang or fail to capture input correctly.
What's Wrong with the Original Code?
- Every time you create a new
ScannerforSystem.in, it shares the same underlying input stream. When you enterningetDetails(), the newline character (\n) you press after typing the number stays in the buffer. The secondScannerindisplayDetails()will try to read this newline first instead of the array elements you're expecting, leading to unexpected behavior or input failures.
Fixed Code
Here's the revised version that reuses a single Scanner instance, eliminating the input conflict:
import java.util.Scanner; class Sample { private int n; // Create one Scanner instance to reuse across methods private Scanner scanner = new Scanner(System.in); public void getDetails() { System.out.print("Enter value for n: "); n = scanner.nextInt(); System.out.println("Entered 'n' = " + n); } public void displayDetails() { int i, j; int arr[] = new int[n]; System.out.println("Enter " + n + " array elements:"); for(j = 0; j < n; j++) { arr[j] = scanner.nextInt(); System.out.println("Entered element = " + arr[j]); } System.out.println("Entered array: "); for(i = 0; i < n; i++) System.out.print(arr[i] + " "); // Optional: Close the scanner if you don't need it anymore // scanner.close(); // Note: Closing System.in Scanner will prevent any further input operations in the program } } public class Test { public static void main(String[] args) { Sample sample = new Sample(); sample.getDetails(); sample.displayDetails(); } }
Key Changes Made:
- Added a single
Scanneras a private member of theSampleclass, initialized once when the class instance is created. - Removed the duplicate
Scannerobjects ingetDetails()anddisplayDetails(), using the sharedscannerinstance instead. - Added clear prompts to guide the user (optional but improves usability).
- Included a note about closing the scanner—be cautious here, as closing it will lock the
System.instream for the entire program.
This approach ensures the input buffer is handled consistently, so your program will read all user inputs as expected.
内容的提问来源于stack exchange,提问作者S4rt-H4K
相关产品推荐
相关产品推荐

