Input Output And Exceptions

Input/Output Exceptions

Attach:exceptions.pdf

Demo0:Pick a Number

import java.util.Scanner;
public class Demo0 
{
	public static void main(String[] args)
	{
		Scanner kb=new Scanner(System.in);
		int number = pickANumber(kb);
		while(number != 0){
			number = pickANumber(kb);
		}
	}
	public static int pickANumber(Scanner kb) 
	{
		System.out.print("Pick a number (0 to quit): ");
		String aNumber=kb.nextLine(); 
		int number=Integer.parseInt(aNumber);
		return number;
	}
}
  1. Type in integers, and all is well... what if you type a double or a String?
  2. Now catch the Exception in the main method
           try {
        	    int number=pickANumber(kb);
                while (number!=0)
                {
                		number=pickANumber(kb);   	   			
                	}
           } catch (Exception e){
        	        System.out.println("Exception Thrown!!!");
    	        System.out.println(e.getMessage()); 
           }
    
  3. Change the pickANumber method so it throws an SillyNumber exception
            public static int pickANumber(Scanner kb) throws SillyNumberException
    	{
    		System.out.print("Pick a number (0 to quit): ");
    			String aNumber=kb.nextLine(); 
    			int number=Integer.parseInt(aNumber);
    		if (number%2==1) throw new SillyNumberException("That's odd...");
    		return number;
    	}
    

Demo1: LineNumberer

import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
public class LineNumberer
{
   public static void main(String[] args)
      throws FileNotFoundException
   {
      Scanner console = new Scanner(System.in);

      System.out.print("Output file: ");
      String outputFileName = console.next();

      JFileChooser chooser = new JFileChooser();
      if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
      {

          FileReader reader = new FileReader(chooser.getSelectedFile() );
          System.out.println("Adding line numbers to "+chooser.getSelectedFile().getName() );
          Scanner in = new Scanner(reader);
          PrintWriter out = new PrintWriter(outputFileName);
          int lineNumber = 1;

          while (in.hasNextLine())
          {
              String line = in.nextLine();
              out.println("/* " + lineNumber + " */ " + line);
              lineNumber++;
          }

          out.close();
          in.close();
        }
   }
}

Any text file like the one below can be used.

Mary.txt

Mary had a little lamb
Whose fleece is white as snow
Everywhere Mary went
Her lamb was sure to go

Demo 2 : Data Analyzer

DataAnalyzer.java

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

/**
   This program reads a file containing numbers and analyzes its contents.
   If the file doesn't exist or contains strings that are not numbers, an
   error message is displayed.
*/
public class DataAnalyzer
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);
      DataSetReader reader = new DataSetReader();

      boolean done = false;
      while (!done) 
      {
         try 
         {
            System.out.println("Please enter the file name: ");
            String filename = in.next();

            double[] data = reader.readFile(filename);
            double sum = 0;
            for (double d : data) sum = sum + d; 
            System.out.println("The sum is " + sum);
            done = true;
         }
         catch (FileNotFoundException exception)
         {
            System.out.println("File not found.");
         }
         catch (BadDataException exception)
         {
            System.out.println("Bad data: " + exception.getMessage());
         }
         catch (IOException exception)
         {
            exception.printStackTrace();
         }
      }
   }
}

DataSetReader.java

import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

/**
   Reads a data set from a file. The file must have the format
   numberOfValues
   value1
   value2
   . . .
*/
public class DataSetReader
{
   /**
      Reads a data set.
      @param filename the name of the file holding the data
      @return the data in the file
   */
   public double[] readFile(String filename) 
         throws IOException, BadDataException
   {
      FileReader reader = new FileReader(filename);
      try 
      {
         Scanner in = new Scanner(reader);
         readData(in);
      }
      finally
      {
         reader.close();
      }
      return data;
   }

   /**
      Reads all data.
      @param in the scanner that scans the data
   */
   private void readData(Scanner in) throws BadDataException
   {
      if (!in.hasNextInt()) 
         throw new BadDataException("Length expected");
      int numberOfValues = in.nextInt();
      data = new double[numberOfValues];

      for (int i = 0; i < numberOfValues; i++)
         readValue(in, i);

      if (in.hasNext()) 
         throw new BadDataException("End of file expected");
   }

   /**
      Reads one data value.
      @param in the scanner that scans the data
      @param i the position of the value to read
   */
   private void readValue(Scanner in, int i) throws BadDataException
   {
      if (!in.hasNextDouble()) 
         throw new BadDataException("Data value expected");
      data[i] = in.nextDouble();      
   }

   private double[] data;
}

BadDataException.java

/**
   This class reports bad input data.
*/
public class BadDataException extends Exception
{
   public BadDataException() {}
   public BadDataException(String message)
   {
      super(message);
   }
}

Data files

The following are different input files. Using your operating systems, place a copy of these data files in the same folder where your IDE stores your project.

bad1.dat

10
1
2
3
4
5
6
7
8
9

bad2.dat

ten
1
2
3
4
5
6
7
8
9

bad3.dat

10
one
2
3
4
5
6
7
8
9

bad4.dat

10
1
2
3
4
5
6
7
8
9
10
11

good.dat

10
1
2
3
4
5
6
7
8
9
10

Demo 3: Car Talk Lab

demo 4: Making QR Codes


Review Exercises


Programming Exercises

Do one of these for 8 points, or both for 10 points.

P3.6.1 Write a program that asks a user for a file name and prints the number of characters, words, and lines in that file. If you use the Mary.txt file above you should get the following output:

Characters: 94
Words: 20
Lines : 4

Use the following class as your main class:

import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JFileChooser;

/**
   This class prints a report on the contents of a file.
*/
public class FileAnalyzer
{
   public static void main(String[] args) throws IOException
   {
      JFileChooser chooser = new JFileChooser();
      if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
      {

        FileReader reader = new FileReader(chooser.getSelectedFile());
        Scanner fileIn = new Scanner(reader);
        FileCounter counter = new FileCounter();
        counter.read(fileIn);
        fileIn.close();
        System.out.println("Characters: " + counter.getCharacterCount());
        System.out.println("Words: " + counter.getWordCount());
        System.out.println("Lines : " + counter.getLineCount());
    }
   }
}

FileCounter.java

import java.util.Scanner;
/**
   A class to count the number of characters, words, and lines in files.
*/
public class FileCounter
{
   /**
    * instance variables
    */
   //your code here...

   /**
      Constructs a FileCounter object.
   */
   public FileCounter()
   {
     //Your code here . . .

   }

   /**
      Processes an input source and adds its character, word, and line
      counts to this counter.
      @param in the scanner to process
   */
   public void read(Scanner in)
   {
      while (in.hasNextLine())
      {
          String line=in.nextLine();
          //Your code here. . .


      }
   }

   /**
      Gets the number of words in this counter.
      @return the number of words
   */
   public int getWordCount()
   {
      //Your code here. . .

   }

   /**
      Gets the number of lines in this counter.
      @return the number of lines
   */
   public int getLineCount()
   {
     //Your code here . . .

   }
   /**
      Gets the number of characters in this counter.
      @return the number of characters
   */
   public int getCharacterCount()
   {
     //Your code here . . .
   }

}

P3.6.2 Write a program that asks the user to input a set of floating-point values. When the user enters a value that is not a number, give the user as many chances as necessary to enter a correct value. Quit the input stage of the program when the user enters a blank input. Add all correctly specified values and print the sum when the user is done entering data. Use exception handling to detect improper inputs.

Here is a sample program run:

Value: 1
Value: 2
Value: three
Input error. Try again.
Value: 3
Value : four
Input error. Try again.
Value: quartre
Input error. Try again.
Value: vier
Input error. Try again.
Value: 4
Value: five
Input error. Try again.
Value: cinq
Input error. Try again.
Value: 5
Value:
Sum: 15.0

Your main class should be called DataReader.

import java.util.Scanner;

public class DataReader
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);

      boolean done = false;
      double sum = 0;

      while (!done)
      {
         try
         {
            // your code here...
         }   
         catch (NumberFormatException e)
         {   
            System.out.println("Input error. Try again.");    
         }
      }

      System.out.println("Sum: " + sum);
   }
}