Page 291 - Cs_withBlue_J_C11_Flipbook
P. 291

Using InputStreamReader
                 We can also use the InputStreamReader to input data in the array. However, like the Scanner class, we need to provide
                 a message before entering the values.
                 Let us see the following program using InputStreamReader.



                   Program 5     Write a program in Java to input five names of different items and their costs in two single
                                 arrays using InputStreamReader and print the names of the items and their costs. Also print
                                 the total cost.

                   1       import java.io.*;
                   2       class item_price

                   3       {
                   4           public static void main() throws IOException

                   5           {
                   6               InputStreamReader isr= new InputStreamReader(System.in);

                   7               BufferedReader br=new BufferedReader(isr);
                   8               String item_name[ ]=new String[5];

                   9               double item_price[ ]=new double[5];
                   10              int i;

                   11              double total=0;
                   12              for(i=0; i<5; i++)

                   13              {
                   14                  System.out.print("Enter name of item no: "+ (i+1) + " : ");

                   15                  item_name[i]=br.readLine();
                   16                  System.out.print("Enter cost of item no: "+ (i+1) + " : ");
                   17                  item_price[i]=Double.parseDouble(br.readLine());

                   18              }

                   19              System.out.println("------------------------------");
                   20              System.out.println("Item Name\tItem Price");
                   21              for(i=0; i<5; i++)

                   22              {

                   23                  System.out.println(item_name[i]+ "\t\t" +item_price[i]);
                   24                  total = total + item_price[i];
                   25              }

                   26              System.out.println("Total price of all items are " +total);
                   27          }

                   28      }



                                                                                                                       289
                                                                                                              Arrays   289
   286   287   288   289   290   291   292   293   294   295   296