Java / Java Basics

Handling User Input with Scanner

In this tutorial, we will explore how to handle user input using the Scanner class in Java. You'll learn how to read different types of input from the user.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers fundamental concepts, including syntax, data types, and basic input/output operations.

1. Introduction

In this tutorial, we will learn how to handle user input using the Scanner class in Java. This class is a convenient way to get input from the user in the console. By the end of this tutorial, you will be able to read different types of input from the user, including strings, integers, and floating-point numbers.

Prerequisites:

  • Basic knowledge of Java programming language
  • JDK installed on your computer
  • A text editor or IDE (like Eclipse or IntelliJ IDEA)

2. Step-by-Step Guide

The Scanner class is part of the java.util package, so we need to import it before using. The Scanner class can read from various input streams including reading from a string or file. In this tutorial, we'll focus on reading from standard input (System.in).

Creating a Scanner object:

To start, we need to create an instance of the Scanner class. Here's the syntax:

Scanner scanner = new Scanner(System.in);

Reading Input:

The Scanner class provides various methods to read different types of data:

  • nextLine(): reads a line of text
  • nextInt(): reads an integer
  • nextDouble(): reads a double
  • next(): reads the next token

Each method advances the scanner past the input that matched.

3. Code Examples

Example 1: Reading a line of text

import java.util.Scanner;  // Import the Scanner class

public class Main {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);  // Create a Scanner object
    System.out.println("Enter your name:");

    String userName = myObj.nextLine();  // Read user input
    System.out.println("Your name is: " + userName);  // Output user input
  }
}

In this example, myObj.nextLine(); waits for the user to input a line of text in the console. The text is then stored in the userName variable, and printed out.

Example 2: Reading an integer

import java.util.Scanner;  // Import the Scanner class

public class Main {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);  // Create a Scanner object
    System.out.println("Enter your age:");

    int userAge = myObj.nextInt();  // Read user input
    System.out.println("Your age is: " + userAge);  // Output user input
  }
}

Here, myObj.nextInt(); waits for the user to input an integer. The integer is then stored in the userAge variable, and printed out.

4. Summary

In this tutorial, we learned how to handle user input using the Scanner class in Java. We have seen how to create a Scanner object, and how to use different methods provided by the Scanner class to read different types of user input.

For further learning, you could explore how to read other types of data like boolean or long, and how to use the Scanner class to read from a file.

5. Practice Exercises

Exercise 1: Write a program that asks the user for their name and age, and prints them.

Solution:

import java.util.Scanner;

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

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

    System.out.println("Enter your age:");
    int age = scanner.nextInt();

    System.out.println("Your name is " + name + " and you are " + age + " years old.");
  }
}

Exercise 2: Write a program that asks the user for two numbers, and prints the sum.

Solution:

import java.util.Scanner;

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

    System.out.println("Enter the first number:");
    int num1 = scanner.nextInt();

    System.out.println("Enter the second number:");
    int num2 = scanner.nextInt();

    int sum = num1 + num2;
    System.out.println("The sum is " + sum);
  }
}

For further practice, you can modify these exercises to handle different types of input, or to perform different operations on the input.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

Fake User Profile Generator

Generate fake user profiles with names, emails, and more.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help