![]() |
![]() |
Java if statement | |
Java if-else statement | |
Java nested if-else | |
Java else-if ladder | |
Java Switch case statement | |
Java Nested Switch Case | |
Java Ternary/Conditional operator |
Java while loop | |
Java do-while loop | |
Java for loop | |
Java Enhanced loop/for each loop | |
Java Labelled for loop | |
Java Nesting of loops | |
Java Break and Continue |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions | |
In java language, we can take the values from the user instead of assigning at the time of compilation.
Java allows us to get values from user throw the keyboard input by using following 3 ways.
Commandline argument is one of the esiest way to take values from user while runnign the program.
Note : We have already studies about the commandline argument.
Second way of getting input from user is by using the scanner class.
Steps for use
Accepting integer from user and displaying using scanner.
import java.util.Scanner; class ScannerTest { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int value; System.out.println("Enter any number : "); value = sc.nextInt(); System.out.println("You have entered : "+value); } }
Java provides several different methods to get different type values as.
Sr. | Method Name | Used For |
---|---|---|
1. | sc.next () | it returns the string from scanner |
2. | sc.nextLine () | it returns the string by moving scanner to next line. |
3. | sc.nextInt () | it returns the integer by scanning value. |
4. | sc.nextFloat () | it returns the float from scanner |
5. | sc.nextDouble () | it returns the double from scanner |
6. | sc.nextByte () | it returns the byte from scanner |
7. | sc.nextShort () | it returns the short from scanner |
8. | sc.next () | it returns the long from scanner |
BufferedReader is mostly used in the file handling concept. BufferedReader have fast performance while taking input from user.
Note: BufferedReader need to type into other type before use.
The method readLine() method generates an exception hence it is written inside the try-catch block.
import java.io.*; class ScannerTest { public static void main(String args[]) { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String value = null; try { value = br.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("You have entered : "+value); } }