Title: PrintStream Scanner More Examples
Course: CPS 261: Advanced Java Concepts ~ DL & MM MASTER

PrintStream Scanner - More complex Input

So far our examples have just been reading Strings through the Scanner class. Its hard to get bad data when we are dealing with Strings. In this section we are going to read input as integers, and doubles. This kind of input has more error situations that we will need to deal with. In order to assist us with some of these issues we will discover some new methods in the Scanner class:

- hasNext()- This method returns a true when we have some data in our buffer. Any String present in the buffer will result in a "true" return. This method is useful to make sure we have not run out of data in our file.
- hasNextInt() - This method returns true if we have some data in our buffer and it fits the definition of an integer ... in otherwords plain digits.
- hasNextDouble() - This method returns true if we have some data in our buffer and it fits the definition of an double ... in otherwords plain digits and the "." character.

Careful Integer Reading

To demonstrate some of these options, we have the following example:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.InputMismatchException;
import java.util.Scanner;


public class CopyIntegers {

    void copyInts(Scanner scanner, PrintStream printStream)
    {
        while (scanner.hasNext())
        {
            int x = scanner.nextInt();
            printStream.println(x);
        }
    }
    void copyInts2(Scanner scanner, PrintStream printStream)
    {
        while (scanner.hasNext())
        {
            try
            {
                int x = scanner.nextInt();
                printStream.println(x);
            }
            catch (InputMismatchException e)
            {
                // Note the following skips over the bad input
                System.out.println(e+ " bad integer: "+ scanner.next());
            }
        }
    }
    void copyInts3(Scanner scanner, PrintStream printStream)
    {
        while (scanner.hasNext())
        {
            int x = -1;
            if (scanner.hasNextInt())
            {
                x = scanner.nextInt();
                printStream.println(x);
            }
            else
            {
                // Note the following skips over the bad input
                System.out.println(" bad integer: "+ scanner.next());
            }

        }
    }


    void process(String inputFileName, String outputFileName)
    {
        Scanner scanner=null;
        PrintStream printStream=null;

        try
        {
            FileInputStream fi = new FileInputStream(inputFileName);
            scanner = new Scanner(fi);
            FileOutputStream fo = new FileOutputStream(outputFileName);

            printStream = new PrintStream(fo);
            copyInts(scanner, printStream);
           // copyInts2(scanner, printStream);
           // copyInts3(scanner, printStream);
        }
        catch (FileNotFoundException e)
        {
            System.out.println("error: "+e);
        }
        finally
        {
            if (scanner != null)
                scanner.close();
            if (printStream != null)
                printStream.close();
        }
    }

    public static void main(String[] args) {
        CopyIntegers ci = new CopyIntegers();
        ci.process(args[0], args[1]);
    }

}


Try reading a file with the following contents:


1 4 7 2
23 77
45
12 34 56 34 235 34 56 78 123 4321 4555



Mixed Data

The following example demonstrates a more complicated scenario where we have Strings, integers and doubles:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.InputMismatchException;
import java.util.Scanner;


public class Printstream_Scanner_Mixed_Data_Examples {
    void readMixedData(Scanner scanner, PrintStream printStream)
    {
        while (scanner.hasNext())
        {
            String name = scanner.next();
            int homeRuns = scanner.nextInt();
            double battingAverage = scanner.nextDouble();

            printStream.printf("%s has %d home runs and has a %.3f batting average%n",
                    name, homeRuns, battingAverage);
        }
    }
    void readMixedData2(Scanner scanner, PrintStream printStream)
    {
        while (scanner.hasNext())
        {
            try
            {
                String name = scanner.next();
                int homeRuns = scanner.nextInt();
                double battingAverage = scanner.nextDouble();

                printStream.printf("%s has %d home runs and has a %.3f batting average%n",
                        name, homeRuns, battingAverage);
            }
            catch (InputMismatchException e)
            {
                System.out.println("Skipping line: "+e);
                scanner.nextLine(); // skip the remainder of the line
            }
        }
    }
    void readMixedData3(Scanner scanner, PrintStream printStream)
    {
        while (scanner.hasNext())
        {
            String name = scanner.next();
            int homeRuns = -1;
            if (scanner.hasNextInt())
                homeRuns = scanner.nextInt();
            else
            {
                // Note the following skips the bad input
                System.out.println("Bad home run input: "+ scanner.next() + " defaulting to -1");
            }
            double battingAverage = -1;
            if (scanner.hasNextDouble())
                battingAverage = scanner.nextDouble();
            else
            {
                // Note the following skips the bad input
                System.out.println("Bad batting average: "+ scanner.next() + " defaulting to -1");
            }

            printStream.printf("%s has %d home runs and has a %.3f batting average%n",
                    name, homeRuns, battingAverage);
        }
    }

    void readMixedData4(Scanner scanner, PrintStream printStream)
    {
        while (scanner.hasNext())
        {
            String name = scanner.nextLine();
            int homeRuns = -1;
            if (scanner.hasNextInt())
                homeRuns = scanner.nextInt();
            else
            {
                // Note the following skips the bad input
                System.out.println("Bad home run input: "+ scanner.next() + " defaulting to -1");
            }
            double battingAverage = -1;
            if (scanner.hasNextDouble())
                battingAverage = scanner.nextDouble();
            else
            {
                // Note the following skips the bad input
                System.out.println("Bad batting average: "+ scanner.next() + " defaulting to -1");
            }

            printStream.printf("%s has %d home runs and has a %.3f batting average%n",
                    name, homeRuns, battingAverage);
            if (scanner.hasNextLine())
                scanner.nextLine();// need to go to the next line
        }
    }

    void process(String inputFileName, String outputFileName)
    {
        Scanner scanner=null;
        PrintStream printStream=null;

        try
        {
            FileInputStream fi = new FileInputStream(inputFileName);
            scanner = new Scanner(fi);
            FileOutputStream fo = new FileOutputStream(outputFileName);

            printStream = new PrintStream(fo);
            readMixedData(scanner, printStream);
        }
        catch (FileNotFoundException e)
        {
            System.out.println("error: "+e);
        }
        finally
        {
            if (scanner != null)
                scanner.close();
            if (printStream != null)
                printStream.close();
        }
    }

    public static void main(String[] args) {
        Printstream_Scanner_Mixed_Data_Examples psme = new Printstream_Scanner_Mixed_Data_Examples();
        psme.process(args[0], args[1]);
    }

}



Consider reading the following data with this program:

Fred 2 0.301
Bubba 28 0.278
Frank 10 0250
Babe 55x 0.320
Ted 19 0.350

Change the process routine to call the readMixedData2 method and see the difference:

Change the process routine again to call the readMixedData3 method.

Suppose we want to read in names that are more variable (i.e. names that 2, 3, or 1 part). For example consider the following file:

Fred E Flintstone
2 0.301
Bubba
28 0.278
Frank F Robinson
 10 0250
Babe Ruth
55x 0.320
Ted Williams
19 0.350


Change the process routine to use the readMixedData4 method.

Last Updated: May 26, 2015 4:28 PM