Skip to main content

Posts

Showing posts from February, 2020

Reading values from Console in Java

How do you read a number from keyboard in Java ? Such a simple question to ask ? Or is it? Funnily reading values from console in Java is not as easy as scanf() or cin in Java Let us write the code import java.util.Scanner ; public class ReadNumber { public static void main ( String args []){ Scanner sc = new Scanner ( System . in ); int num = sc . nextInt (); int num2 = sc . nextInt (); System . out . println ( "Second number is " + num2 ); System . out . println ( "The number is " + num ); } } You need to use the class Scanner and call its constructor with System.in. Then you have to call various methods to read like scanner.nextInt(), scanner.nextFloat() etc. I remember writing programs using BufferedInputReader. Which was quite lengthy and needed throw block. Compared to input, displaying the output in Java is quite simple. You just need to use System.out.println