You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 Scanner for System.in, it shares the same underlying input stream. When you enter n in getDetails(), the newline character (\n) you press after typing the number stays in the buffer. The second Scanner in displayDetails() 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 Scanner as a private member of the Sample class, initialized once when the class instance is created.
  • Removed the duplicate Scanner objects in getDetails() and displayDetails(), using the shared scanner instance 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.in stream 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:59:41