In Java, reading input from the user or from external sources is a crucial part of many programs. In this tutorial, we'll explore various methods to obtain input in Java, ensuring that users can interact with your programs effectively. We'll cover the following topics:
The most common way to read input in Java is by using the Scanner class from the java.util package. Here's a step-by-step guide on how to use it:
import java.util.Scanner; public class InputExample { public static void main(String[] args) { // Create a Scanner object Scanner scanner = new Scanner(System.in); // Prompt the user for input System.out.print("Enter your name: "); // Read a line of text from the user String name = scanner.nextLine(); // Display the input System.out.println("Hello, " + name + "!"); // Don't forget to close the scanner scanner.close(); } }
This code snippet demonstrates how to read a line of text from the user and display it. Remember to close the Scanner object when you're done to prevent resource leaks.
To read numeric input such as integers or floating-point numbers, you can use methods like nextInt(), nextDouble(), or nextFloat() from the Scanner class:
import java.util.Scanner; public class NumericInputExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); int number = scanner.nextInt(); System.out.print("Enter a floating-point number: "); double decimal = scanner.nextDouble(); System.out.println("You entered: " + number + " and " + decimal); scanner.close(); } }
You can read multiple inputs on the same line or in sequence, depending on your program's requirements:
import java.util.Scanner; public class MultipleInputsExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter your age: "); int age = scanner.nextInt(); scanner.nextLine(); // Consume the newline character System.out.print("Enter your name: "); String name = scanner.nextLine(); System.out.println("Hello, " + name + "! You are " + age + " years old."); scanner.close(); } }