Habenero Java

Click here for the previous tutorial.

The Scanner is a method of recieving user input, by having them type it right into the console, then send it to a variable that you have chosen within your code. The syntax of this can be a little tricky, as you declare it once, and then call it when you need input, and then close it when finished.

Scanner scannerName = new Scanner(System.in);

Here we are declaring the Scanner. The only thing that ever changes here is scannerName. You can call it anything you could normally call a variable, just be simple, concise, and consistant.

String password = scannerName.next();

this sets the String password to whatever is typed by the user. If you had questions about last tutorial, this hopefully answered some of them.

int intName = scannerName.nextInt();

This sets the integer intName equal to whatever is typed. Note that this does not check for the validity of the entry; if the user were to enter a letter or symbol, it would crash the program.

float floatName = scannerName.nextFloat();

Assigns whatever is entered to float type floatName. This, like the integer entry, does not check validity.

There are checks that can be done to validate any sort of primitive data type within a scanner. Generally, it follows a simple form.

scannerName.hasNext(Type)()

In order to check for an int type then, we may want to create a simple test before possibly crashing the program.

if(scannerName.hasNextInt()){
    intName = scannerName.nextInt();
}

Now you may have been experiencing an error with the Scanner up until this point. You have probably checked your spelling three times, you might have pulled out some hair, and you are about ready to give up. I am going to fix this problem. This is caused because the type Scanner is made in one of Java's own pieces of code. By default, your compiler is not exactly sure where Scanner is. you have to use the import command. In eclipse, you can simply hover over the error, and the first suggestion should be to import. Otherwise, you can also hit ctrl+shift+o to import. If neither work, do not worry, bucause you can very easily do it manually.

import java.util.Scanner;

Just type that above your class declaration. I would advise having a blank line between the two for cleanliness.

Finally, the last command is to close your Scanner. When you are entirely done with it, probably towards the end of the program, just use this simple command.

scannerName.close();

Click here to coninue to the next tutorial.