Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Java User Input in Java

Java User Input in Java

User Input in Java

In Java, user input is typically handled using the Scanner class, which is part of the java.util package. The Scanner class provides methods to read input of various types like strings, integers, and floating-point numbers from the user.

Here’s a guide on how to use Scanner for user input in Java.


1. Importing the Scanner Class

To use the Scanner class, you need to import it at the top of your Java file:

import java.util.Scanner;

2. Creating a Scanner Object

Next, you create a Scanner object to read input from the console:

Scanner scanner = new Scanner(System.in);

Here, System.in represents the standard input stream (keyboard).


3. Reading Different Types of User Input

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

a. Reading Strings

You can read a line of text using the nextLine() method:

String name = scanner.nextLine();System.out.println("Hello, " + name);

b. Reading Integers

You can read an integer value using the nextInt() method:

int age = scanner.nextInt();System.out.println("You are " + age + " years old.");

c. Reading Floating-Point Numbers

You can read a floating-point number using the nextFloat() or nextDouble() methods:

double price = scanner.nextDouble();System.out.println("The price is $" + price);

d. Reading a Single Word

If you want to read just a single word (without spaces), you can use the next() method:

String word = scanner.next();System.out.println("You entered the word: " + word);

4. Closing the Scanner

It’s a good practice to close the Scanner object when you're done using it to free up resources. This is done using the close() method:

scanner.close();

5. Complete Example

Here's a complete example that demonstrates how to get user input for different types of data:

import java.util.Scanner;public class UserInputExample {    public static void main(String[] args) {        // Create Scanner object        Scanner scanner = new Scanner(System.in);                // Reading a String        System.out.print("Enter your name: ");        String name = scanner.nextLine();                // Reading an Integer        System.out.print("Enter your age: ");        int age = scanner.nextInt();                // Reading a Double (floating-point number)        System.out.print("Enter your height (in meters): ");        double height = scanner.nextDouble();                // Output the values entered by the user        System.out.println("\nUser Info:");        System.out.println("Name: " + name);        System.out.println("Age: " + age);        System.out.println("Height: " + height);                // Close the scanner        scanner.close();    }}

Explanation:

  1. Name Input: The program first asks the user to input their name using nextLine().

  2. Age Input: The program then asks for an integer (age) using nextInt().

  3. Height Input: Finally, the program asks for the user’s height using nextDouble().

  4. After all inputs, it prints the entered values.

  5. It closes the Scanner object to release the resources.


Handling Input Issues:

If the user inputs something of the wrong type (e.g., entering a string when the program expects an integer), it can cause an InputMismatchException. You can handle this exception using try-catch blocks.

Example: Handling Input Mismatch

import java.util.Scanner;public class InputMismatchExample {    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);                System.out.print("Enter your age: ");                try {            int age = scanner.nextInt();            System.out.println("You are " + age + " years old.");        } catch (Exception e) {            System.out.println("Invalid input! Please enter a valid integer.");        } finally {            scanner.close();        }    }}

In this example, if the user enters something that is not an integer, the program will print an error message and prevent the program from crashing.


Let me know if you'd like to explore more about user input or if you have any specific questions!

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql