USER INPUT IN JAVA
User inputs are the most needed and commonly seen things in
any program. User inputs gives us the flexibility of storing the values inside
the variables given by the user after
running the program, instead of initialising the variables at the first place. So
as we talked earlier about importing packages and classes, for taking a user
input we first need to import the scanner class or simply the whole package
(which already contains the scanner class).
Ex:
import java.util.*;
or
import
java.util.Scanner;
After
importing the scanner class or the whole package, we can create a Scanner class
object. For creating a scanner object look at the example below.
Ex:
Scanner
sc = new Scanner(System.in);
After
creating the scanner object we can use it to take inputs. For taking inputs we
will use ‘sc.nextInt()’ method. But for different datatypes we have different
methods. The table given below shows us the different methods used to take the
inputs for different types.
boolean |
nextBoolean(); |
short |
nextShort(); |
Int |
nextInt(); |
long |
nextLong(); |
byte |
nextByte(); |
double |
nextDouble(); |
float |
nextFloat(); |
String |
nextLine(); |
Now
many of you might be thinking that there is no method to take a character input
in java. Unfortunately yes, java doesn’t have any direct method to take a
character input but who says we can’t take one? For taking a character as input
look at the example below:
Ex:
Char
ch = sc.next().charAt(0);
So in the above example the scanner method reads a string from the input, but only returns a single letter, since it has a ‘charAt()’ method with the index 0 , so here basically a string gets created in which we are using only the 0 index.
Hope you are clear on this topic do read our more articles on JAVA LANGUAGE.
If you still have any doubt on this topic then do come to us via email "sophomoretechs@gmail.com" or via Instagram "@coding.winds".
This article is SUBMITTED By : Pranjal Rai
Do subscribe to our daily blog update by clicking here.
Thank You!
No comments:
Post a Comment