Different ways to read input from console in Java
using IO Streams
import java.io.*;
class aa
{
public static void main(String sd[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("enter first no");
String s1=br.readLine();
int a=Integer.parseInt(s1);
System.out.print("enter second no");
String s2=br.readLine(); //s2 is a string that is read from console
int b=Integer.parseInt(s2); //s2 is converted to data type int b
System.out.print("sum="a+b);
}}
Description :
import java.io.*: It is a import package statement in which IO package is used wit all classes by
using (*)
InputStreamReader :is a class of IO package to accept the input from user
BufferedReader is class is Reads text from a character-input stream, buffering characters for the efficient reading of characters.
readLine: method is a static method of Java Console class. It is used to reads a single line of text from the console.example br.readLine() "br is an object of BufferedReader"
Integer.parseInt:The method generally used to convert String to Integer in Java is parseInt().
Java User Input (Scanner)
import java.util.*; //util is a package that contain Scanner class
class scn
{
public static void main(String sd[])
{
Scanner sn = new Scanner(System.in);
System.out.print("enter first no");
int a=sn.nextInt(); //nextInt is a method to read int value from user
System.out.print("enter second no");
int b=sn.nextInt();
System.out.print( a+b);
}}
Note:-If you enter wrong input you will get exception message like "InputMismatchException"
Example:- 2
public class scn2 {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();//using nextLine method to print string
System.out.println("Your Name is: " + name);
}
}
No comments:
Post a Comment