K
PRO
last month
Kartikcountry asked

How to accept user input in Java?

Udayan Shakya
Expert
last month
Udayan Shakya answered

Hello, Kartik! You take user input by creating an object of the Scanner class, and then using the object to call the appropriate method, such as nextInt() for integers, nextDouble() for floating-point numbers, and nextLine() for strings.

For example,

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        
        System.out.println("Enter your age: ");
        
        // Create a Scanner object
        Scanner input = new Scanner(System.in);
        
        // Take user input 
        int age = input.nextInt();
        
        System.out.println("Age is " + age);

    }
}

The basics of user input has already been explained in the Taking Input lesson of Chapter 1: Introduction.

Please review that lesson again before proceeding further.

Hope that helps! Contact us again if you have further questions.

Java
This question was asked as part of the Learn Java Basics course.