Core elements of programs - Input

Introduction

Up until now, things have been cool and all but a bit too… predictable. Like the code stuff’s cool but… you always knew what was going too happen, and it was all the same. Well, fear no longer! If you haven’t read the title yet, this lesson is about inputting data into a program.

We’re also going to do our first import this lesson. How exciting!

Java comes with code to take input from the console, in the “Scanner” class.

You’ll want to create a new variable of type “Scanner”, with the value of a new Scanner instance.

This is done in roughly the same way that you create an integer, string, or other object.

Here’s an example below:

 Scanner keyboardInput = new Scanner(System.in);

That creates a new variable, of type Scanner, called keyboardInput, and sets it value to…. a new Scanner. We need to give Scanner some information, which is what we want to scan. Thus we give it “System.in”

Now you might notice some red squigly lines below “Scanner”. That’s because, although Java has code for a Scanner, we haven’t actually told it we want to use that code.

Not to fear; simply hover over the word Scanner, and click “import Scanner (Java.util)”. This will conveninently import the code for a Scanner into your code.

Now to do some scanning…

calling keyboardInput.nextLine() will return a String of what has been typed into the console. Take a look at the example code:

 Scanner keyboardInput = new Scanner(System.in);
 
System.out.print("What is your name? ");
String name = keyboardInput.nextLine();
System.out.println("Hello " + name);

Activities

  1. Ask someone their first and last name. Then impersonate them James Bond style (e.g. if they gave “James” and “Bond”, say “The name’s Bond. James Bond.”).
  2. Ask someone their favourite number. Respond with a number twice as big as theirs.

    “nextLine” returns a String, but here you want a number. if you type “scan.” then press “Ctrl + Space” eclipse will show you a list of all the different functions (things) a Scanner can do. There’s a lot, but if you type in “next” it will only show you functions that start with “next”, cutting down the list to only useful things. You can use the arrow keys to scroll up and down the list, and hit enter to select your option.