HOME HTML EDITOR C JAVA PHP

Java Scanner Methods

In Java, the Scanner class is used to take input from the user. It is very useful when we want to read data like numbers, strings, or characters from the keyboard.

The Scanner class belongs to the java.util package, so we must import it before using it.

1. Importing Scanner

import java.util.Scanner;

2. Creating a Scanner Object

To use Scanner, we need to create its object.

Scanner sc = new Scanner(System.in);

Here, System.in is used to take input from the keyboard.

3. nextLine()

The nextLine() method reads a full line of text.

System.out.print("Enter your name: "); String name = sc.nextLine(); System.out.println("Hello " + name);

4. next()

The next() method reads only one word (until space).

System.out.print("Enter your city: "); String city = sc.next(); System.out.println(city);

5. nextInt()

The nextInt() method reads an integer value.

System.out.print("Enter your age: "); int age = sc.nextInt(); System.out.println("Age: " + age);

6. nextDouble()

The nextDouble() method reads a decimal (double) number.

System.out.print("Enter your marks: "); double marks = sc.nextDouble(); System.out.println("Marks: " + marks);

7. nextFloat()

The nextFloat() method reads a float value.

float price = sc.nextFloat();

8. nextLong()

The nextLong() method reads a long value.

long mobileNumber = sc.nextLong();

9. nextBoolean()

The nextBoolean() method reads a boolean value (true or false).

boolean result = sc.nextBoolean();

10. hasNextInt()

The hasNextInt() method checks if the next input is an integer.

if(sc.hasNextInt()) { int number = sc.nextInt(); }

Important Note About nextLine()

Sometimes after using nextInt() or nextDouble(), the nextLine() method may skip input.

To solve this, add an extra sc.nextLine(); after numeric input.

int age = sc.nextInt(); sc.nextLine(); // clear buffer String name = sc.nextLine();

Closing the Scanner

After using Scanner, it is good practice to close it.

sc.close();

Why Scanner is Important?

Conclusion

The Scanner class provides many methods like nextInt(), nextLine(), nextDouble(), and more to take user input.

It is one of the most commonly used classes in Java programming.

Tip: Always close the Scanner object after use to avoid resource leaks.