CSC224 Apr03

slide version

single file version

Contents

  1. Simple Input with Scanner
  2. If Statements: Example 1
  3. Comparing instances of Class types
  4. If Statement: Example 2
  5. Comparing Strings: Example
  6. If statement: Example 2
  7. Formated printing of Strings
  8. If statement Example 3
  9. Example 3 (cont.)
  10. Read input from standard input
  11. Scanner: Input with a sentinel
  12. Sentinel Example (cont.)
  13. Reading Input without a Sentinel
  14. Example Reading Input without a Sentinel
  15. Reading Input From a File
  16. Creating a Scanner associated with a File
  17. Scanner Input from a File:
  18. Reading from a File (cont.)
  19. Comments on using hasNextInt
  20. Scanner: Reading whole lines
  21. Random Class
  22. For Loop Example
  23. For Loop Example (cont.)
  24. Simple Graphics

Simple Input with Scanner[1] [top]

    1   import java.util.Scanner;
    2   
    3   /**
    4    * Description: Finds the maximum of two input integers.
    5    * 
    6    * @author glancast
    7    * 
    8    */
    9   public class Max2 {
   10   
   11     public static void main(String[] args) {
   12       int n, m;
   13       int max;
   14       Scanner input = new Scanner(System.in);
   15   
   16       System.out.println("This program computes the maximum of two input integers");
   17       System.out.printf("\nFirst integer: ");
   18       n = input.nextInt();
   19       System.out.printf("\nSecond integer: ");
   20       m = input.nextInt();
            ...
          }
        }

If Statements: Example 1[2] [top]

    1   
    2   import java.util.Scanner;
    3   
    4   /**
    5    * Description: Finds the maximum of two input integers.
    6    * 
    7    * @author glancast
    8    * 
    9    */
   10   public class Max2 {
   11   
   12     public static void main(String[] args) {
   13       int n, m;
   14       int max;
   15       Scanner in = new Scanner(System.in);
   16   
   17       System.out.println("This program computes the maximum of two input integers");
   18       System.out.print("\nFirst integer: ");
   19       n = in.nextInt();
   20       System.out.print("\nSecond integer: ");
   21       m = in.nextInt();
   22   
   23    if (n < m) {
   24         max = m;
   25       } else {
   26         max = n;
   27       }
   28       System.out.printf("The larger of %d and %d is %d\n", n, m, max);
   29   
   30     }
   31   
   32   }

Comparing instances of Class types[3] [top]

The usual comparison operators: ==, <, <=, >=, != used to compare basic numeric types would compare addresses if used for Class types.

Every class type has a method for equality testing:

        public boolean equals(Object x)
      

For some class types, the idea of an ordering makes no sense. E.g., what would it mean for one Scanner instance to be less than another Scanner instance.

So the operators <, <=, >, >= only make sense for class with an ordering.

For every class type for which there is a natural ordering, the class will have a method:

public int compareTo(Object x)  
      

For example, strings are ordered in the usual alphabetic (lexicographic) ordering:

So the String class has the compareTo method in addition to the equals method.

If Statement: Example 2[4] [top]

To compare Strings or any class type, use the compareTo method.

Comparing Strings: Example[5] [top]

        String s1 = "cat";
        String s2 = "car";
        String s3 = "catch";

        s1.compareTo(s2) is > 0  s1 comes after s2
        s1.compareTo(s3) is < 0  s1 comes before s3
        s1.compareTo("cat") is 0    s1 is equal to "cat"
        s1.equals(s2) is false
        s1.equals(s1) is true
        s1.equals("cat") is true
      

If statement: Example 2[6] [top]

Find the largest of three input strings. That is, the string that comes last in the natural ordering of strings.

    1   public class Max3 {
    2   
    3    
    4     public static void main(String[] args) {
    5       String s1, s2, s3;
    6       String max;
    7       Scanner input = new Scanner(System.in);
    8   
    9       System.out.println("This program computes the smallest of three input strings");
   10       System.out.println("That is, it prints the string that comes last in the usual " +
   11           "ordering of strings.");
   12       System.out.println();
   13       
   14       System.out.printf("\nFirst string: ");
   15       s1 = input.next();
   16       System.out.printf("\nSecond string: ");
   17       s2 = input.next();
   18       System.out.printf("\nThird string: ");
   19       s3 = input.next();
   20       
   21       max = s1;
   22       if ( s2.compareTo(max) > 0  ) {
   23         max = s2;
   24       }
   25       if (s3.compareTo(max) > 0 ) {
   26         max = s3;
   27       }
   28       ...
   29       
   30     }
   31   }

Formated printing of Strings[7] [top]

    1   public class Max3 {
    2   
    3    
    4     public static void main(String[] args) {
    5       String s1, s2, s3;
    6       String max;
    7       Scanner input = new Scanner(System.in);
    8       ....
    9       max = s1;
   10       if ( s2.compareTo(max) > 0  ) {
   11         max = s2;
   12       }
   13       if (s3.compareTo(max) > 0 ) {
   14         max = s3;
   15       }
   16       System.out.printf("For strings '%s', '%s', and '%s', %s comes last in the usual ordering.",
   17           s1, s2, s3, max);
   18       
   19     }
   20   }

If statement Example 3[8] [top]

Write a method String letterGrade(int score) that returns the letter grade for a test.

The letter grade should be computed from the score by

   A: >= 94
   B: >= 85
   C: >= 76
   D: >= 67
   F: >= 0
      

Example 3 (cont.)[9] [top]

    1   public class GradeComp {
    2   
    3     public static String letterGrade(int score) {
    4       String grade;
    5       if ( score >= 94 ) {
    6         grade = "A";
    7       } else if ( score >= 85 ) {
    8         grade = "B";
    9       } else if ( score >= 76 ) {
   10         grade = "C";
   11       } else if ( score >= 67 ) {
   12         grade = "D";
   13       } else {
   14         grade = "F";
   15       }
   16       return grade;
   17     }
   18     
   19     public static void main(String[] args) {
   20       int score;
   21       String grade;
   22       Scanner input = new Scanner(System.in);
   23       
   24       System.out.print("Enter a test score: ");
   25       score = input.nextInt();
   26       
   27       grade = letterGrade(score);
   28       
   29       System.out.printf("For numeric score %d, the grade is %s", score, grade);
   30     }
   31   }

Read input from standard input[10] [top]

The Scanner class has methods hasNext(), hasNextInt(), etc. that return a boolean depending on whether the next input of the indicated type is on the input.

For input from standard input (the keyboard), hasNext must wait for the user to type in some value. So it simply doesn't return until the user does so.

Instead of using the hasNext() method, the programmer can choose a special value (e.g. -1) for the user to enter to mean no more input.

The special value will only indicate the end of input and will not be processed otherwise.

Such a special value is called a "sentinel".

Scanner: Input with a sentinel[11] [top]

Read non-negative integers from standard input until the user enters a value of -1, the sentinel to signal end of input.

Count the values read (not including the sentinel) and print the count and the maximum value read.

Sentinel Example (cont.)[12] [top]

    1   import java.util.Scanner;
    2   
    3   public class SentinelInput {
    4   
    5     public static void main(String[] args) {
    6       
    7       Scanner input = new Scanner(System.in);
    8       int max = 0, n;
    9       final int SENTINEL = -1;
   10       System.out.println("This program will read integers from standard input and print " +
   11           " number of values read and the largest value.");
   12       System.out.printf("\nTo signal end of input, enter a sentinel value of -1\n\n");
   13       
   14       int count = 0;
   15       System.out.print("input value> ");
   16       n = input.nextInt();
   17       max = n;
   18       while( n != SENTINEL ) {
   19         count++;
   20         if ( n > max ) {
   21           max = n;
   22         }
   22a        n = input.nextInt();
   23       }
   24       System.out.printf("There were %d values read.\n", count);
   25       if ( count > 0 ) {
   26         System.out.printf("The maximum value read was %d\n", max);
   27       }
   28          
   29     }
   30   }

Reading Input without a Sentinel[13] [top]

An appropriate sentinel value may not exist.

If the previous program processed all integers - negative as well as non-negative, there are no integer values left to use as a sentinel.

The hasNext family of Scanner methods can be used to detect end of input.

Note that hasNextInt() will return false at end of input or if the next input is doesn't represent an int.

The hasNext methods return false instead of throwing an exception if the input is not what is expected.

Example Reading Input without a Sentinel[14] [top]

    1   import java.util.Scanner;
    2   
    3   public class SentinelInput {
    4   
    5     public static void main(String[] args) {
    6       
    7       Scanner input = new Scanner(System.in);
    8       int max = 0, n;
   10       System.out.println("This program will read integers from standard input and print " +
   11           " number of values read and the largest value.");
   12       System.out.printf("\nTo signal end of input, type ctrl-z (or ctrl-d)\n\n");
   13       
   14       int count = 0;
   15       System.out.print("input value> ");
   16       while( input.hasNextInt() ) {
   17         n = input.nextInt();
   18         if ( count == 0 ) {
   19            max = n;
   20         } else {
   21           if ( n > max ) {
   22             max = n;
   23           }
   24         }
   25         count++;
   26       }
   27       System.out.printf("There were %d values read.\n", count);
   28       if ( count > 0 ) {
   29         System.out.printf("The maximum value read was %d\n", max);
   30       }
   31          
   32     }
   33   }

    

Reading Input From a File[15] [top]

Almost the same code can be used to read integers from a file.

The only difference is in the creation of the Scanner.

After that, the code is the same.

Creating a Scanner associated with a File[16] [top]

import java.util.Scanner;

    1   public static void main(String[] args) {
    2       String fileName;
    3       Scanner input = new Scanner(System.in);
    4       Scanner infile = null;
    5       int max = 0, n;
    6       
    7       System.out.println("This program will read integers (negative, non-negative) and print the largest value.");

   10       fileName = input.next();
   11       
   12       // Try to create a Scanner for the file name entered
   13       try {
   14         infile = new Scanner(new File(fileName));
   15       } catch(FileNotFoundException e) {
   16         System.out.printf("Unable to open input file %s\n", fileName);
   17         System.exit(1);
   18       }
   19       ...
   20   }

Scanner Input from a File: [17] [top]

To count and find the maximum of integers in an input file, we need to first set up the Scanner.

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

    1   public static void main(String[] args) {
    2       String fileName;
    3       Scanner input = new Scanner(System.in);
    4       Scanner infile = null;
    5       int max = 0, n;
    6       
    7       System.out.println("This program will read integers from a file and print the largest value.");
    8       System.out.printf("\nEnter the input file name: ");
    9       
   10       fileName = input.next();
   11       
   12       // Try to create a Scanner for the file name entered
   13       try {
   14         infile = new Scanner(new File(fileName));
   15       } catch(FileNotFoundException e) {
   16         System.out.printf("Unable to open input file %s\n", fileName);
   17         System.exit(1);
   18       }
   19       ...
   20   }

Reading from a File (cont.)[18] [top]

Once a Scanner is created for a file of integers, the Scanner hasNextInt() method can be used as the while loop test for end of input.

The initialization of the max should be the first value read (if the file is not empty). This changes the code a bit from the sentinel example:

    1   public class SimpleFileInput {
    2   
    3     /**
    4      * @param args
    5      */
    6     public static void main(String[] args) {
    7       String fileName;
    8       Scanner input = new Scanner(System.in);
    9       Scanner infile = null;
   10       int max = 0, n;
   11       
   12       System.out.println("This program will read integers from a file and print the largest value.");
   13       System.out.printf("\nEnter the input file name: ");
            ...
            /* code to create a Scanner for infile goes here, but is not shown */
            ...
   24       int count = 0;
   25       while(infile.hasNextInt()) {
   26         if (count == 0) {
   27           max = infile.nextInt();
   28         } else {
   29           n = infile.nextInt();
   30           if ( n > max ) {
   31             max = n;
   32           }
   33         }
   34         count++;
   35       }
   36       System.out.printf("There were %d values read from input file %s.\n", count, fileName);
   37       if ( count > 0 ) {
   38         System.out.printf("The maximum value read was %d\n", max);
   39       }
   40          
   41     }
   42   }

Comments on using hasNextInt[19] [top]

What happens if the input file has some integers but then has a typo such as u6 instead of 86?

What happens to the example with the sentinel example?

Scanner: Reading whole lines[20] [top]

Since the Scanner next() method stops as soon as it encounters whitespace (a blank, tab, newline, carriage return) it can't be used directly to read a line that contains blanks such as a person's full name.

The Scanner class has a nextLine() method that reads the entire line. It returns the input line as a single String. The returned string does not include the end of line character.

Random Class[21] [top]

Instead of manually creating a text file of integers for testing, the Random class has a method to create pseudo random sequences of integers or doubles and the other numeric types. It also lets you restrict the range of the numbers generated; e.g. you may only want values in the range 0 to 100 in one case or 2 to 12 in another case (two dice).

        Random r = new Random();
        int x;

        x = r.nextInt(101); // x will be a random int with 0 <= x < 101
        y = r.nextInt(11);  // y will be a random int with 0 <= y < 10
      

For Loop Example[22] [top]

Use the Random class and a for loop to create exactly 1000 values in the range 1 to 100 (not 0 to 99) and count the number of values <= 50. It should be about 500 if the random numbers are distributed uniformly in the range 1 to 100.

For Loop Example (cont.)[23] [top]

    1   import java.util.Random;
    2   
    3   public class RandomTester {
    4   
    5     public static void main(String[] args) {
    6       Random r = new Random();
    7       final int NGEN = 1000;
    8       final int TOPVALUE = 100;
    9       int count = 0;
   10       int n;
   11   
   12       // Generate NGEN random numbers, each in the range 1 to TOPVALUE 
   13       for(int i = 0; i < NGEN; i++ ) {
   14         n = r.nextInt(TOPVALUE) + 1;
   15         if ( n <= TOPVALUE/2 ) {
   16           count++;
   17         }
   18       }
   19       System.out.printf("Of %d random numbers, each in the range 1 to %d\n" +
   20           "%d were less than or equal to %d", NGEN, TOPVALUE, count, TOPVALUE/2);
   21     }
   22   
   23   }

Simple Graphics[24] [top]

Using two classes, you can create a graphical window and draw shapes and/or text in it.

The two classes are:

The JFrame class creates a window that 'frames' other items.

You can't draw or place text directly on a JFrame instance.

A JComponent is an item that can be added to a JFrame; i.e., inside the 'frame'.

A simple graphical program

But, there are some additional things going on.