Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to pass input from a console to a Java program ?.


In this section of blog, we will look into a tutorial and a simple Java program, explaining how to pass input from a console to a Java program. Usually, Input is given to the program from the standard input device called as keyboard. In Java reading an input is not as simple as output. Java API is full of several classes which can be used for the purpose of reading the input from a keyboard.

System.in is a predefined stream object which can be used to read input. But System.in is a byte oriented stream, it can be used only to read bytes. In order to make it read characters we usually wrap it across a character oriented stream called as InputStreamReader. InputStreamReader is a reader class which is been used to read characters. For reading the input as string we wrap this byte stream to BufferedReader which buffers characters.

In order to apply above concepts to these streams we follow these steps :


1. BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));

2. InputStreamReader isr = new InputStreamReader(
System.in);
BufferedReader br = new BufferedReader(isr);


In order to read a string, we use method readLine on the BufferedReader object as

String read = br.readLine();

Program to demonstrate how to pass input from console to a Java program in order to calculate sum and average of numbers as wished by user

package com.hubberspot.streams.example;

import java.io.*;
public class ConsoleReader {

public static void main(String[] args) throws IOException {

int number, sum=0, n, i;
float avg;

BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));

System.out.println("How many numbers? ");

n = Integer.parseInt(br.readLine());

 for(i=0; i < n ; i++)
{
System.out.println("Enter number " + (i+1));

number = Integer.parseInt(br.readLine());
sum += number;
}

avg = sum / n;

System.out.println("Sum of numbers is = " + sum);
System.out.println("Average of numbers is = "+ avg);

}
} 


Output of the program :





 
© 2021 Learn Java by Examples Template by Hubberspot