how to use input in java

www.lautt‮.iru‬com
how to use input in java

To use input in a Java program, you can use the Scanner class, which is a utility class provided by the Java API that allows you to read data from an input stream, such as the keyboard or a file.

Here's an example of how you can use the Scanner class to read input from the keyboard in Java:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); // Create a Scanner object to read from the keyboard

        System.out.print("Enter your name: "); // Prompt the user for input
        String name = scanner.nextLine(); // Read a line of text from the keyboard

        System.out.print("Enter your age: "); // Prompt the user for input
        int age = scanner.nextInt(); // Read an integer from the keyboard

        System.out.println("Hello, " + name + "! You are " + age + " years old."); // Print the input data
    }
}

In this example, the Scanner class is used to read a line of text (the user's name) from the keyboard and an integer (the user's age) from the keyboard. The nextLine and nextInt methods are used to read different types of data from the input stream.

You can use the Scanner class to read different types of data from the input stream, such as strings, integers, floating-point numbers, boolean values, and more. You can also use the Scanner class to read data from a file or other input sources, by providing the appropriate input stream as an argument to the Scanner constructor.

Note that the Scanner class is a utility class and cannot be instantiated directly. You need to create an instance of the Scanner class to use it. You can use the close method of the Scanner class to close the input stream and release any resources associated with it when you are done reading data from it.

Created Time:2017-11-01 22:29:47  Author:lautturi