Search code examples
javauser-input

How can I receive user input in Java in a single line in the console


I am attempting to make a simple text-based calculator application in Java. I am wondering if it would be possible to take input inline with a print statement. for instance, instead of getting an input like this:

Enter Number One:
num
Enter Number Two:
num

I was wondering if I could get input similar to how it is done in Python, like this:

Enter Number One: num
Enter Number Two: num

Any help would be appreciated.

I am attempting to get input in one line in Java rather than in 2 lines.


Solution

  • You can use below code to take input in same line

    public static void main(String[] args) {
    
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter Number One: ");
        int num1 = scanner.nextInt();
        System.out.print("Enter Number Two: ");
        int num2 = scanner.nextInt();
    
    }
    

    Sample output of above code is

    Enter Number One: 10
    Enter Number Two: 20