user1793408
user1793408

Reputation: 113

How do I handle IOExceptions?

I am a student and this is my second week of Java. the assignment is to get data from the keyboard, for a student name, ID, and three test scores. Then display the primary data using JOptionPane. I believe that I have all of that done. I've taken the assignment a little further so that I can learn about unit testing as well.

The problem is that the ID and test scores are supposed to be numbers. If a non-numeric value is entered I get IOExceptions. I think I need to use try/catch but everything I have seen so far is leaving me confused. Could someone please break down how the try/catch works so that I can understand it?

//Import packages
import java.io.*;
import java.util.Scanner;
import javax.swing.JOptionPane;

/**
 *
 * @author Kevin Young
 */

public class StudentTestAverage {

    //A reusable method to calculate the average of 3 test scores
    public static double calcAve(double num1, double num2, double num3){
        final double divThree = 3;
        return (num1 + num2 + num3 / divThree);
    }

    //A method to turn a doule into an integer
    public static int trunAve(double num1){
        return (int) num1;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException{
        //Input variables
        String strStudentName = "";
        int intStudentID = 0;
        double dblScore1 = 0.0;
        double dblScore2 = 0.0;
        double dblScore3 = 0.0;
        String strNumber = ""; //Receives a string to be converted to a number

        //Processing variables
        double dblAverage = 0.0;
        int intAverage = 0;

        /**
         * Create objects that read keyboard data from a buffer
         */

        //Create the reader and Buffer the input stream to form a string
        BufferedReader brObject = 
                new BufferedReader(new InputStreamReader(System.in));

        //Get the student's name
        do{
            System.out.print("Please enter the student's name?");
            strStudentName = brObject.readLine();
        }while(strStudentName.equals(""));

        //Use the scanner to get the student ID
        //this method converts the string to an Integer
        Scanner scan = new Scanner(System.in);

        do{
            System.out.print("Please enter the student's ID?");
            intStudentID = scan.nextInt();
       }while(Double.isNaN(intStudentID));
       /*
        * The above do while loop with the Scanner isn't working as
        * expected. When non-numeric text is entered it throws an 
        * exception. Has the same issue when trying to use parseInt().
        * Need to know how to handle exceptions.
        */


       /**
        * Us JOption to get string data and convert it to a double
        */
        do{
            strNumber = JOptionPane.showInputDialog("Please enter the first test score?");
            dblScore1 = Double.parseDouble(strNumber);
        }while(Double.isNaN(dblScore1));

        do{
            strNumber = JOptionPane.showInputDialog("Please enter the second test score?");
            dblScore2 = Double.parseDouble(strNumber);
        }while(Double.isNaN(dblScore2));

        do{
            strNumber = JOptionPane.showInputDialog("Please enter the third test score?");
            dblScore3 = Double.parseDouble(strNumber);
        }while(Double.isNaN(dblScore3));

        //Calculate the average score
        dblAverage = calcAve(dblScore1, dblScore2, dblScore3);

        //Truncate dblAverage making it an integer
        intAverage = trunAve(dblAverage);


        /**
         * Display data using the JOptionPane
         */
        JOptionPane.showMessageDialog(
                null, "Student " + strStudentName + " ID " + 
                Integer.toString(intStudentID) + " scored " +
                Double.toString(dblScore1) + ", " + 
                Double.toString(dblScore2) + ", and " +
                Double.toString(dblScore3) + ".\n For an average of " +
                Double.toString(dblAverage));

        //Output the truncated average
        System.out.println(Integer.toString(intAverage));
    }
}

Upvotes: 4

Views: 182

Answers (5)

Maddy
Maddy

Reputation: 2224

The problem is you are using nextInt() method which expects an integer as input. You should either validate user inputs or give the user specific instructions to input valid numbers.

Using try catch in java:

Exception is simply execution of instructions in a unintended/unexpected way. Java handles exceptions by try,catch clause. Syntax is as follows.

try{  

//suspected code

}catch(Exception ex){

//resolution

} 

Put your suspected code that might throw an exception inside the try block. And inside the catch block, put the code that resolves a problem if something would go wrong while executing the suspected code.

You can find a comprehensive explanation here and a summarized version here.

Upvotes: 1

Ahmet Karakaya
Ahmet Karakaya

Reputation: 10147

You should not use try-catck block to check number format. It is expensive. You may use following code portion. It could be more usefull.

    String id;
    do{
        System.out.print("Please enter the student's ID?");            
        id = scan.next();
        if(id.matches("^-?[0-9]+(\\.[0-9]+)?$")){
            intStudentID=Integer.valueOf(id);
            break;
        }else{
            continue;
        }

   }while(true);

Upvotes: 1

Yair Zaslavsky
Yair Zaslavsky

Reputation: 4137

I recommend you wrap only code that throws the exception, and not wrap tons of lines with code.
At the catch block you should consider what to do if you have IOException.
You can have only one catch block as suggested by @Quoi,
But you may consider having different catch blocks per exception
(bare in mind that the order of the catch blocks should be in such a way that subclasses come first). For example, at some application I developed,
some exceptions were severe, so we stopped handling, and some were not severe, so we continued to the next phase.
So our catch blocks set a boolean flag whether to continue or not to the next stage.

Upvotes: 0

Mordechai
Mordechai

Reputation: 16302

Try this:

 do{
     try{
        System.out.print("Please enter the student's ID?");
        intStudentID = scan.nextInt();
     }catch(IOException e){
         continue; // starts the loop again
     }
 }while(Double.isNaN(intStudentID));

Upvotes: 0

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41230

try{
  // code that may throw Exception
}catch(Exception ex){
 // catched the exception
}finally{
 // always execute
}

do{
    try{
      System.out.print("Please enter the student's name?");
      strStudentName = brObject.readLine();
    }catch(IOException ex){
       ...
    }
}while(strStudentName.equals(""));

Upvotes: 2

Related Questions