Page 330 - CITS - Computer Software Application -TT
P. 330

COMPUTER SOFTWARE APPLICATION - CITS



           Sometimes, it’s necessary to verify if the next value we’re about to read is of a specific data type or if the input has
           reached its end (EOF marker encountered).
           To accomplish this, we can utilise the hasNextXYZ() functions, where XYZ represents the type we are interested
           in. These functions return true if the Scanner has a token of the specified type, and false otherwise. For example,
           in the code below, we have employed hasNextInt() to check for an integer input. To check for a string, we use
           hasNextLine(), and for a single character, we use hasNext().charAt(0)
           Let’s review a code snippet for reading numbers from the console and calculating their mean
           // Java program to read some values using Scanner
           // class and print their mean.
           import java.util.Scanner;

            public class ScannerDemo2 {
               public static void main(String[] args)
               {
                   // Declare an object and initialise with
                   // predefined standard input object

                   Scanner sc = new Scanner(System.in);
                    // Initialize sum and count of input elements
                   int sum = 0, count = 0;
                    // Check if an int value is available
                   while (sc.hasNextInt()) {

                       // Read an int value
                       int num = sc.nextInt();
                       sum += num;
                       count++;

                   }
                   if (count > 0) {
                       int mean = sum / count;
                       System.out.println(“Mean: “ + mean);
                   }
                   else {

                       System.out.println(
                           “No integers were input. Mean cannot be calculated.”);
                   }
               }

           }
           This Java program reads integer values from the standard input using the Scanner class and calculates their
           mean (average). Here’s a breakdown of how the program works:
           1  It imports the Scanner class to facilitate user input.
           2   In the main method
              •  It creates a Scanner object sc to read input from the standard input stream (System.in).

              •  Initialises two variables, sum and count, to keep track of the sum of input values and the count of input
                 values, respectively.


                                                           317
                               CITS : IT&ITES - Computer Software Application - Lesson 78 - 84





  78
   325   326   327   328   329   330   331   332   333   334   335