Lecture 10: Scanner Class Solution
Scanner problem statement
Implement a Scanner class data type, scanner1, so that Java asks for your height in metres
Scanner solution
Scanner scanner1 = new Scanner(System.in);
double height = scanner1.nextDouble();
Scanner output
What is your height? 1,65
You are 1.65 m
Hi there, This is Marius from AlefTav Coding. Today, I will look at the Scanner class coding exercise. Your homework was to Implement a ‘Scanner’ class data type, ‘scanner1’, so that Java asks for your height in metres
I want my program to read information typed in at my keyboard. Therefore I have to declare a Scanner object with the name, scanner1. This scanner1 holds a reference to a new instance of Java's Scanner class. Java needs the Scanner import. (import java.util.Scanner)
The information read in is a decimal number. Hence, my declaration is of data type, double, which is named, height. I take the value scanned in, and make a call to the method, nextDouble(). The value returned by nextDouble() is then stored at the location, height.
import java.util.Scanner;
public class Lecture10 {
public static void main(String[] args) {
System.out.print(“What is your height? ”);
Scanner scanner1 = new Scanner(System.in);
double height = scanner1.nextDouble();
System.out.print(“Your profession: ” + job);
}
}
I have a class, here, Lecture10 with a main() method. Then I do a print statement, asking the user to enter their height as a decimal value. This is followed by an implementation of the Scanner class, named, scanner1. Then I do an implementation of the primitive data type, double, named, height.
Next, I confirm that the details typed in by the user is correct by doing a printout, System.out.print(“Your profession: ” + job);. The first part of the String is the text, You are. Then I add the user's height with the plus (+) symbol. I also add the string, m, which is the shortened form of metres.
Then, my program is completed by the addition in my solution of the Scanner import, (import java.util.Sannner;).
With the code being correct, the program is executed. The output is the question being asked, What is your height?. I provide an answer, 1,65. Java then responds with the string, You are 1.65 metres.
In this lecture you learnt the solution to the Scanner coding exercise. Next time I will show you how to implement the conditional statement known as the 'Ternary' operator.
I am Marius, from AlefTav Coding. Till the next time, KEEP CODING.
If you found this tutorial helpful, please upvote, subscribe, like and share. You can find me at the following links.
https://www.udemy.com/course/1435298/manage/basics/
https://d.tube/#!/c/mariusclaassen
https://steemit.com/@mariusclaassen