Lecture 9: Scanner Class Example
Example problem statement
Implement a ‘Scanner’ class data type, ‘input’, so that Java asks for your profession.Example solution
Scanner input = new Scanner(System.in);
String job = input.nextLine();
Example output
What is your profession? Java teacher
Your profession: Java teacher
Hi there, I am Marius from AlefTav Coding. Today I will look at an example of letting your program get user input. You will learn how to 'Implement a ‘Scanner’ class data type, ‘input’, so that Java asks for your profession.'
import java.util.Scanner;
public class Lecture9 {
public static void main(String[] args) {
System.out.print(“What is your profession? ”);
Scanner input = new Scanner(System.in);
String job = input.nextLine();
System.out.print(“Your profession: ” + job);
}
}
Java's 'Scanner' class lets the user interact directly with the program. Here, I have a 'Scanner' declaration. The name I have given it is 'input'. Then, I create what is known as an 'object' with the expression 'new Scanner'. Next I initialize 'input' to this new object. With this statement Java is able to accept information typed by the user on their keyboard.
Notice the word 'in''. With Java output, the computer 'System' prints something 'out'. But with Java input, the computer 'System' reads something 'in'.
To use the 'Scanner' data type Java requires extra information. This information is obtained from the 'java.util' sub-folder by means of an 'import' statement that must appear before the start of the program.
Java needs to store the information typed in by the user. The 'job' information that the user provides is a piece of text. So, Java stores it as a String data type. And 'job' is initialized with the line of text provided through the method, 'nextLine()'
I hava a class, here, 'Lecture9' with the method, main(). Then, I print some text on the screen. This text is a question asked by Java. In this case, what my profession is. At this point, Java waits for the user to type in an answer to the question.
Then, here, Java prints the information provided by the user. This is to confirm that Java correctly read in the information. This text is printed and then I add the profession name stored at the location, 'job'.
After my code is complete I run the program. Java is asking what my profession is. I reply, 'Java teacher'. And Java repeats these details, 'Your profession: Java teacher'.
In this lecture you learnt how to implement the Scanner class. Next, you can go ahead to do this coding exercise:
Scanner coding exercise:
Implement a Scanner class data type, scanner1, so that Java asks for your height in metres
My name is Marius from AlefTav Coding. Till next time, KEEP CODING.
Please feel free to upvote, comment, subscribe and share
▶️ DTube
▶️ IPFS