Skip to main content

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(String)

e.g.

System.out.println("Hello world");

But what if we want to print a number?

This number should be converted to string by using String.valueOf(number)

e.g.
int m = 10;
System.out.println(String.valueOf(m));

What if we want to print a string and some numbers?

Then just concat these using + operator.

int m = 10
System.out.println("m is "+m);


Comments