Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java programming: 1) a) Write a method throws IOException and InvalidFormatExcep

ID: 3848076 • Letter: J

Question

Java programming:

1) a) Write a method throws IOException and InvalidFormatException.This method takes Scanner object as parameter. Returns: numba of non-empty lines from Scanner object. Throw InvalidFormatException if line has invalid integer and throw IOException if there exists a empty file line.

b) Write main method that opens file and creates scanner object for that file. Call the method created in a). You must show how the method from a) can be called in the main() (handle exceptions in main()).

Explanation / Answer

Program Code:

import com.sun.media.sound.InvalidFormatException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

/**
*
* @author SuNiL
*/
public class ShowException {
public void readData() throws FileNotFoundException,IOException,InvalidFormatException{
Scanner in=new Scanner(new FileReader("C:\Users\SuNiL\Desktop\Values.txt"));//variable to read input from file
String val;//variable to store each line content
while(in.hasNext()){//checking if more line of data available in the file
try{
val=in.nextLine();//getting the line content
if(val.isEmpty()){//checking if the line is empty
throw new IOException();//creating object for IOException if line is empty
}else{
System.out.println(Integer.parseInt(val));//converting data into integer
}
}catch(NumberFormatException nf){//catching exception
System.out.println("Number format exception");
}catch(IOException io){
System.out.println("Input output exception");
}
}
}
public static void main(String args[]) throws IOException{
ShowException se=new ShowException();//creating object
se.readData();//function to read file data
}
}

Input:

34
as

67
12
12.4

Output:

run:
34
Number format exception
Input output exception
67
12
Number format exception

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote