Read Input from console in java, Scanf Equivalent in Java

From PU/ Programming in Java

Asked on 28 Dec, 2020

Like 0 Dislike 500 Views

How to scanf in java? explained with example?

Add a comment

2 Answers

Anonymous on 30 Dec, 2020 Like 1 Dislike

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);
}

}

comments on the answer (1)

Like 1 Dislike import* AIYANA KOIRALA on 8 Dec, 2021

Add a comment

arjun adhikari on 28 Dec, 2020 Like 0 Dislike

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 a comment


Add your answer