Input everything
A large part of programming is letting code output/print to the console and inputting/entering our own data into the console.
This way, the program can use what we give it for a response, decision, etc. And the way we do that is with the Scanner.
Scanner
Scanner is a class we need to import from the Java utility library. That sounds very confusing and complicated, but it's just this line:
import java.util.Scanner;
class Main {
Make sure you put it at the top of your class/file.
Now we can use Scanner! Let's make a Scanner object that can receive input:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
We are going to learn more about objects later, but let's break this down into plain English:
"Create a Scanner object named input that is a new Scanner that receives System.in.
We talked about System.out when printing to the console. That is a type of output; it's something we receive.
But in this case, since we want to give the program something, we want to provide input, so we use System.in.
From here, we can now write the following:
Scanner input = new Scanner(System.in);
System.out.println("What is your name?");
String name = input.nextLine();
System.out.println("Hi there, " + name + "!");
Let's break this down:
- We print a statement asking for your name
- We set the variable
nameequal toinput.nextLine() - We print a message with
name
So what does nextLine() do? nextLine() is a method of the Scanner object, input we created. It takes the input of the line you type on and returns it as a String, setting the name variable in the process.
Here's a quick reference for some options you can use to receive other types of data types:
String->nextLine()double->nextDouble()int->nextInt()char->nextChar()
Remember to set these to a variable with the same data type or errors.
Scanner doesn't mean too much to us until we learn how to use conditionals to make decisions, but it's helpful to understand how we can use this for input.
Let's do one more practice:
Scanner input = new Scanner(System.in);
System.out.println("What is your name?");
String name = input.nextLine();
System.out.println("Hi " + name + ", how old are you?");
int age = input.nextInt();
System.out.println("Wow, " + age + ", that's great!");
Hopefully, you now understand how Scanner works and enter data into the console.