Input data from the keyboard
Java does not have a reserved word to access input for user. In order to prompt a user to enter a value from the keyboard, we need to import a class called Scanner which is in the package java.util.
To import the class Scanner in your program, you should copy and paste this import statement before the class definition in your java program. import java.util.Scanner;. Once you import this class in your program, to make use of it you need to create an object of a class Scanner before prompting an user to enter anything for the keyboard. Here is the statement to create an object inputof the class Scanner.
Scanner input = new Scanner(System.in); This statement means that we have create an object of class Scanner which take input from the keyboard.
I guess so far so good with the use of Scanner class. The next question is how to use this object of class Scanner in my program?
Remember any values that you want to enter from the keyboard need to be stored in the memory and processed based of the set of instructions you give to the computer. To do that, you need to declare a variable first and store the data into the variable. Here is a statement to store a integer in a variable grade from the keyboard.
int grade = input.nextInt();
input.nextInt() allows the object of the class Scanner input to access or use the method nextInt() of the class Scanner to take an integer value from the keyboard and that value is store in the variable grade.
Notice that the data type of the variable grade is int and the method nextInt() also only take in integer value. If you declare an integer value and store a name into it the compiler will through an error because you can't store a letter into a variable.
List of Scanner methodnext(): accept String from the user such as name, or any word you type from your keyboard.
Example, String name= input.next(); This statement s ore a word that you type from your keyboard and store it in the variable name. With this logic in mind, guess the action performed by each of the method below:
nextDouble()
nextFLoat()
nextChar()
Display data to the screen
To display data from the screen, Java uses the method system.out.print("data to be printed here between double quote if it is a string data type");
system.out.print(data to be printed here if i is an integer of floating point data type without a double quote);
system.out.print('data to be printed here between a single quote if it is a character data type');
For instance this statement displays Java is fun in your screen
System.out.print("Java is fun");Trick
System.out.println() is used when you want the next character to be printed to a next line that is to say not in the same line with the previous display.