USER INPUT IN JAVA

Maha

USER INPUT IN JAVA

The Scanner class is used to get user input, and it is found in the java.util package.

The java.util package should be import while using the Scanner class.

It is used to read the input of primitive types such as int, double, long, short, float, and byte. It is the easiest way to read input in the Java program.

In java, we used the nextLine() method, which is used to read Strings. In read other types such as;

👉🏻 nextBoolean() - Reads a boolean value from the user.

👉🏻 nextByte() - Reads a byte value from the user.

👉🏻 nextInt() - Reads a int value from the user.

👉🏻 nextFloat() - Reads a float value from the user.

👉🏻 nextDouble() - Reads a double value from the user.

Syntax:

import java.util.Scanner;

Example:

import java.util.Scanner;

public class UserInputExample 

{

public static void main(String[] args) 

{

Scanner scanner = new Scanner(System.in);

System.out.print("Enter your name: ");

String name = scanner.nextLine();

System.out.print("Enter your age: ");

int age = scanner.nextInt();

System.out.println("Hello, " + name + "! You are " + age + " years old.");

scanner.close();

}

}

Output:

Enter your name: max

Enter your age: 20

Hello, max! You are 20 years old.


Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send