Today I will teach you all about the scanner library. I used the scanner library in my last post, but I just realized that you may not yet know what it does! A scanner is a pre-programmed object in java that allows you to input data from the user. To be able to use a scanner in your program, you must first type the following code into your program before the start of the class:
import java.util.Scanner;
That will tell java that you want to use the scanner library for your code. Now that you have imported the scanner, you will need to create a scanner in your code:
Scanner scan = new Scanner(System.in);
This will create a new scanner named scan. Now that you have a new scanner, you can input data from the user. If you want a integer, you type:
int i = scan.nextInt();
For a double, you type:
double d = scan.nextDouble();
For a single word, you type:
String s = scan.next();
For multiple words, you type:
String m = scan.nextLine();
There is one problem with the next line method that you need to be aware of for your code to work properly; if you have a scanner method followed by a nextLine method, the nextLine method will not run. To solve this problem, you add another nextLine that is not attached to anything. This line will then be skipped instead of the line that you needed to run. The second error that you need to look out for is if the user enters a invalid data type. You can solve this problem by using the has method. The has method will check to see if the input is the correct data type and return a boolean value. Here are the has methods:
hasNext()
hasNextLine()
hasNextDouble()
hasNextInt()
Each of these methods check for the the corresponding return type. This is pretty much the basics for the scanner method, so hopefully you have learned a thing or two about the scanner method in java, and please post any questions that you have about anything that I have said in this or any other post in the comments below.
No comments:
Post a Comment