Java Scanner User Input Example

The Scanner class is used to read Java user input. Java Scanner is built into the java.util package, so no external libraries are needed to use it. Scanner reads text from standard input. This text is returned to the main program so it can be stored or otherwise manipulated.


Understanding how to get user input in Java is a crucial skill. For instance, say you are building an app with a sign-in form. You will need to handle user input to collect the login credentials for the user.

In Java, you can use the Scanner class to receive user input that you can then process in your program. This tutorial will discuss, using a few examples, how to utilize the Java Scanner class to receive user input.

Java Scanner Class

The Java Scanner class is used to collect user input. Scanner is part of the java.util package, so it can be imported without downloading any external libraries. Scanner reads text from standard input and returns it to a program.

In order to work with the Scanner class, you must first import it into your code. There are two ways you can do this:

  1. If you only need to work with the java.util.Scanner class, you can import the Scanner class directly.
  2. If you are working with other modules in the java.util library, you may want to import the full library.

The following is the code for each of the above methods:

import java.util.Scanner; import java.util.*;

The first line of code imports the Scanner class. The second line of code imports all the packages within the java.util library, including Scanner.

It's worth noting that there are other ways to receive user input data in Java. You can use Java's BufferedReader, InputStreamReader, DataInputStream, and Console classes.

81% of participants stated they felt more confident about their tech job prospects after attending a bootcamp. Get matched to a bootcamp today.

The average bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their first job.

However, the Scanner class is the most popular method of collecting user input in Java. So, we will be focusing on that class in this article.

Java User Input Syntax

You can collect user input using the Scanner class. The Scanner class reads text that a user inserts into the console and sends that text back to a program. Scanner is the primary method of collecting Java user input.

After you import the Java Scanner class, you can start to use it to collect user input. Here is the syntax for the Java Scanner class:

Scanner input = new Scanner(System.in); int number = input.nextInt();          

In this example, we created a variable called input that collects the next value the user inputs into the console. Then we created a variable called number that collects the value the user submits to the console.

Java User Input Example

For instance, suppose we are building an application for a local computer store that keeps track of their inventory.

The manager asked us to create a simple program that she can use to add items to the shop's inventory list. The manager wants to be able to input two values: the name of the item and its quantity.

Here's the code we would use to create this program:

form-submission

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Get exclusive scholarships and prep courses
import java.util.Scanner;  class Main { 	public static void main(String[] args) { 		Scanner input = new Scanner(System.in);  		System.out.print("Product name: "); 		String product_name = input.next(); 		System.out.print("Value entered: " + product_name);  		System.out.print("Quantity: "); 		int quantity = input.nextInt(); 		System.out.print("Value entered: " + quantity); 	} }          

The first input we accept the name of the item. This will be a string because the item names are text-based and use a variety of characters. In the code below, we define this string with the code: String product_name.

The next input is the quantity of the item. This will be a number. In the code below, we define this number with the code: int quantity, where int stands for integer.

When we run our code and insert a few example values, the program returns the following response:

Product name: 15-inch MacBook Pro 2019

Value entered: 15-inch MacBook Pro 2019

Quantity: 7

Value entered: 7

As you can see, our program collected the user's input. It then returned to the console the value the user entered. This allows us to verify that our program is working.

How our Scanner Java Program Works

Let's break down our code step-by-step.

  1. We import the Scanner library into our code so that we can receive user input.
  2. We declare a class called Main that stores the code for our program.
  3. We initialize the Scanner class using Scanner input = new Scanner(System.in); The input Java variable stores our initialized scanner.
  4. We print out "Product name: " to the console and ask the user to submit a product name using input.next();.
  5. We print out to the console the product name the user submitted.
  6. We print out Quantity: to the console and prompt the user to submit the quantity of the product in stock using input.nextInt();.
  7. We print out the value of the quantity variable to the console.

Notice that we used different code to collect numbers and strings. When we collected the product name, we used input.next();, and when we collected the product quantity, we used input.nextInt();.

Java Scanner: Input Types

In our above example, we collected two types of data from the user: a string and an integer. As mentioned, we had to use different code to collect these types of data.

Venus profile photo

"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"

Venus, Software Engineer at Rockbot

Different types of data, like strings and integers, are collected using separate methods. So, to collect a boolean, you'll use different code than you would to collect a float.

Here is a table showing all the methods used to collect user input in Java using the Scanner class:

Method Type of Value the Method Collects
nextBoolean() boolean
nextByte() byte
nextDouble() double
nextFloat() float
nextInt() int
nextLine() String
nextLong() long
nextShort() short

If you insert the wrong input type, your program will raise an InputMismatchException. For example, if you try to insert a double into a field that collects Booleans, your program will raise an exception.

Collecting a Boolean Value

Let's go back to the computer store. Suppose we wanted to update our first program and allow our computer store manager to input whether the product is on display or held in the stockroom.

To do so, we want to collect a new value called on_display that will store input as a Boolean because it can have only two values: true or false.

Here's the code we could use to collect this data:

import java.util.Scanner;  class Main { 	public static void main(String[] args) { 		Scanner input = new Scanner(System.in);  		System.out.print("Product name: "); 		String product_name = input.next(); 		System.out.print("Value entered: " + product_name);  		System.out.print("Quantity: "); 		int quantity = input.nextInt(); 		System.out.print("Value entered: " + quantity);  System.out.print("On display: "); 		boolean on_display = input.nextBoolean(); 		System.out.print("Value entered: " + on_display); 	} }          

When we run our code and insert a few example values, the program returns the following response:

Product name: 15-inch MacBook Pro 2019

Value entered: 15-inch MacBook Pro 2019

Quantity: 7

Value entered: 7

On display: true

Value entered: true

Our program works in the same way as our example above. However, this time we collect an additional value from the user: whether the product they inserted into the program is on display. We use the nextBoolean() method to collect this value from the user. Then we print that value to the console.

Conclusion

You can use Java's Scanner class to collect input from a user. The Scanner class is capable of collecting a variety of data types from users, including short values, Strings, booleans, and others.

In this tutorial, using a few examples, we explored how to use the Java Scanner class to collect user input. In addition, we discussed the different data types offered by the Scanner class that we can use to collect user input.

To learn more about coding in Java, read our How to Code in Java guide.

castelliterettly.blogspot.com

Source: https://careerkarma.com/blog/java-input/

0 Response to "Java Scanner User Input Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel