How to handle IOExceptions?

I am a student and this is my second week of Java. purpose - to receive data from the keyboard, student name, identifier and three test points. Then display the raw data using JOptionPane. I believe that all this is done. I took the task a little further to learn about unit testing.

The problem is that identification and test scores must be numbers. If a non-numeric value is entered, I get IOExceptions. I think I need to use try / catch, but everything I've seen so far leaves me confused. Can someone please break how try / catch works so that I can figure it out?

//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 name do{ System.out.print("Please enter the student 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 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)); } } 
+4
source share
5 answers

You cannot use the try-catck block to check the number format. It is expensive. You can use the following part of the code. This may be more helpful.

  String id; do{ System.out.print("Please enter the student ID?"); id = scan.next(); if(id.matches("^-?[0-9]+(\\.[0-9]+)?$")){ intStudentID=Integer.valueOf(id); break; }else{ continue; } }while(true); 
+1
source
 try{ // code that may throw Exception }catch(Exception ex){ // catched the exception }finally{ // always execute } do{ try{ System.out.print("Please enter the student name?"); strStudentName = brObject.readLine(); }catch(IOException ex){ ... } }while(strStudentName.equals("")); 
+2
source

The problem is that you are using the nextInt () method, which expects an integer as input. You must either check the user input or give instructions for entering the correct numbers.

Using try catch in java:

An exception is simply executing instructions in an unintended / unexpected way. Java handles exceptions with try, catch. The syntax is as follows.

 try{ //suspected code }catch(Exception ex){ //resolution } 

Put your suspicious code that might throw an exception in the try block. And inside the catch block, put code that solves the problem if something goes wrong when the suspicious code is executed.

You can find a comprehensive description here and a generalized version here .

+1
source

Try the following:

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

I recommend that you wrap only the code that throws the exception, and not wrap tons of lines of code.
In the catch block, you should consider what to do if you have an IOException.
You can only have one catch block suggested by @Quoi,
But you might consider having different catch blocks for exception
(without taking into account that the order of catch blocks must be such that subclasses come first). For example, in some application that I developed, some exceptions were serious, so we stopped processing, and some were not serious, so we continued the next step.
Thus, our catch blocks set a logical flag whether to continue or not proceed to the next step.

0
source

Source: https://habr.com/ru/post/1443591/


All Articles