Asked on 28 Dec, 2020
0
959 Views
How to scanf in java? explained with example?
mport java.util.Scanner;
public class ReadString { public static void main (String args[]) {
String str,str1;
Scanner x =new Scanner(System.in);
Scanner y =new Scanner(System.in);
System.out.println("Enter an fname");
str=x.nextLine();
System.out.println("Enter an lname");
str1=y.nextLine();
System.out.println(" name is: "+str+" "+str1);
}
}
There is no any method as scanf of C in Java.
In java, we can read single line of input from console(as a string) and parse it to other data types as per our requirements.
An example of reading an integer value from console is given below:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ReadConsoleSystem {
public static void main(String[] args) {
int age;
System.out.println("Enter your age : ");
try{
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
//Reading single input line as string
String input = bufferRead.readLine();
//parsing read string to desired data type, here to integer
age = Integer.parseInt(input);
System.out.println("Your age is: " + age);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Add your answer