How to Take Input From User Separated By Space in Java

1. Introduction

Taking input from the user is a common requirement in many Java applications. Sometimes, the input might consist of multiple values separated by spaces, such as names, numbers, or other data. Java provides several ways to handle this, but one of the most straightforward methods involves using the Scanner class. This blog post will demonstrate how to take multiple inputs separated by space using the Scanner class in Java.

2. Program Steps

1. Import the Scanner class from the java.util package.

2. Create an instance of the Scanner class to read from System.in.

3. Prompt the user to enter data separated by spaces.

4. Use the nextLine() method of the Scanner instance to read the entire line of input.

5. Split the input string into individual tokens based on spaces.

6. Process and display the tokens.

3. Code Program

import java.util.Scanner;

public class UserInputSpaceSeparated {
    public static void main(String[] args) {
        // Step 1: Importing Scanner class and Step 2: Creating Scanner instance
        Scanner scanner = new Scanner(System.in);

        // Step 3: Prompting the user
        System.out.println("Enter items separated by spaces:");

        // Step 4: Reading the entire line of input
        String inputLine = scanner.nextLine();

        // Step 5: Splitting the input string into tokens
        String[] items = inputLine.split(" ");

        // Step 6: Processing and displaying the tokens
        System.out.println("You entered:");
        for (String item : items) {
            System.out.println(item);
        }

        // Closing the scanner
        scanner.close();
    }
}

Output:

Enter items separated by spaces:
apple banana cherry
You entered:
apple
banana
cherry

Explanation:

1. The program starts by importing the Scanner class, which is used to read the user's input from the standard input stream (System.in).

2. An instance of Scanner named scanner is created to read the input.

3. The user is prompted to enter items separated by spaces. This could be anything like words, numbers, etc.

4. The nextLine() method reads the entire line of input as a single string. This is necessary because the user's input could contain multiple items separated by spaces.

5. The input string is then split into individual tokens (items) using the split(" ") method. The space character is used as the delimiter.

6. The program iterates over the array of tokens using an enhanced for-loop and prints each item. This demonstrates how the input string was successfully separated into individual parts.

7. Finally, the Scanner instance is closed to prevent resource leaks. This is a good practice when working with classes that handle system resources.

Comments