Taking User inputs in Java.





You designed a game that involves two players and the players have to enter their name themselves before starting the game. Java has a special tool that invokes the keyboard when it needs to take an input from the user.

This special tool used to accept input is called Scanner.

Scanner is a class which needs to be imported.


import java.util.Scanner;

 

 

Without this package, you will run into an error. This is done in between your main package and the class.

 

package com.techwithme;

import
java.util.Scanner; //Package for getting the scanner class

public class
Main {
   
public static void main(String[] args) {
       

    }
}

 

To Use the scanner in your main method.

package com.techwithma;

import
java.util.Scanner;

public class
Main {
   
public static void main(String[] args) {
        Scanner input =
new Scanner(System.in);// Instance of the scanner
   
}
}

 

We first call the class which is Scanner and we give it any name of our choice “input” then we instantiate it to new Scanner(System.in).

It is very necessary to Type your scanner in a capital letter.

The above codes is just responsible for Instantiating a Scanner class. To be able to use it your code, You have to indicate in your code the specific type of data your Scanner will accept. Either it being a String, int, float, long, char or many more.

This is done by the following useful methods in the Scanner class.

Read a byte – nextByte()

Read a short – nextShort()

Read an int – nextInt()

Read a long – nextLong()

Read a float – nextFloat()

Read a double – nextDouble()

Read a boolean – nextBoolean()

Read a complete line(String) – nextLine()

Read a word – next()

This method will make the program wait for the user to enter a matching value.

The code might seems complex but you will understand it all in the upcoming lessons.

For more clarification and understanding, watch the video above and don’t forget to subscribe to keep this project running.

 

Challenge!! Write a program that takes the users name and age and prints it on the console.

Code flow.

Output        => Enter your name

Input           => John

Output         => Enter your age

Input              =>  17

Final Output   => Hello John, you are 17 years old.

 

Drop your code in the comment section or send it to me on WhatsApp via https://wa.me/0546651113

You can write your problem and confusion in the comment section below and I will attend to you as soon as possible.

 

GENERAL CHALLENGE


Try your hands on this after completing all the basic lessons in Java.