Java: Read Keyboard Input with Scanner

Java Tutorial: Reading Keyboard Input with Scanner

Java Tutorial: Reading Keyboard Input with Scanner

This tutorial will guide you through the basics of reading keyboard input in Java using the Scanner class. The Scanner class allows your program to receive data from the user’s keyboard, such as strings, integers, and floats. We’ll build three progressively complex examples to solidify your understanding.

Example 1: Reading a Single String

This first example demonstrates how to read a single string from the user. We’ll use the nextLine() method of the Scanner class to read the entire line of text entered by the user, including spaces.

import java.util.Scanner;

public class ReadString {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        System.out.println("Hello, " + name + "!");

        scanner.close();
    }
}

Explanation:

  • We import the java.util.Scanner class.
  • We create a Scanner object named scanner, which is associated with the standard input stream (System.in).
  • We use System.out.print() to prompt the user to enter their name.
  • We use scanner.nextLine() to read the entire line of text that the user enters. This includes any spaces.
  • We store the entered name in a string variable called name.
  • Finally, we print a greeting message to the console using the name.
  • We close the scanner to release resources.

Common Mistakes:

  • Forgetting to import Scanner: If you forget to import the `Scanner` class, the compiler will not recognize the `Scanner` object, leading to a compilation error.
  • Not closing the Scanner: It’s good practice to close the scanner when you are finished with it to release system resources. This can be done by calling `scanner.close()`.

Input:

John Doe

Output:


Enter your name: John Doe
Hello, John Doe!

Example 2: Reading an Integer

Now, let’s read an integer from the user. We’ll use the nextInt() method of the Scanner class to read an integer value.

import java.util.Scanner;

public class ReadInteger {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter an integer: ");
        int number = scanner.nextInt();

        System.out.println("You entered: " + number);

        scanner.close();
    }
}

Explanation:

  • Similar to the previous example, we import the Scanner class.
  • We create a Scanner object named scanner.
  • We prompt the user to enter an integer using System.out.print().
  • We use scanner.nextInt() to read an integer value from the input stream. This method will throw an InputMismatchException if the user enters something that is not an integer.
  • We store the integer in a variable called number.
  • We print the number to the console.
  • We close the scanner.

Common Mistakes:

  • Not handling InputMismatchException: If the user enters a value that is not an integer (e.g., “hello”), the nextInt() method will throw an InputMismatchException. It’s good practice to handle this exception using a try-catch block to prevent your program from crashing.

Input:

10

Output:


Enter an integer: 10
You entered: 10

Example 3: Reading a Float

This example demonstrates reading a floating-point number (a number with decimal places) from the user using the nextDouble() method.

import java.util.Scanner;

public class ReadFloat {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a float: ");
        double pi = scanner.nextDouble();

        System.out.println("You entered: " + pi);

        scanner.close();
    }
}

Explanation:

  • We import the Scanner class.
  • We create a Scanner object named scanner.
  • We prompt the user to enter a float using System.out.print().
  • We use scanner.nextDouble() to read a double value from the input stream. This method also throws an InputMismatchException if the user enters something that is not a double.
  • We store the double value in a variable called pi.
  • We print the float to the console.
  • We close the scanner.

Common Mistakes:

  • Not handling InputMismatchException: Similar to reading an integer, if the user enters non-numeric data, nextDouble() will throw an InputMismatchException.

Input:

3.14159

Output:


Enter a float: 3.14159
You entered: 3.14159

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies and similar technologies to enhance your experience on wobizdu.com, analyze site traffic, personalize content, and deliver relevant ads. Some cookies are essential for the site to function, while others help us improve performance and user experience. You may accept all cookies, decline optional ones, or customize your settings. Review our Privacy Policy to learn more.