Question

In: Computer Science

create your own function that wraps it with try catch. Pass in the string to parse,...

create your own function that wraps it with try catch. Pass in the string to parse, and the name of the field, put some logging in the catch

How do I do this? say with this code segment?

void readStudents() {
//Scanner class object declare
Scanner readStudentFile = null;
//try block begin
try {
//open file
readStudentFile = new Scanner(new File(".\\src\\test\\student.txt"));
//loop until end of file
while(readStudentFile.hasNextLine()) {
String stu = readStudentFile.nextLine();
String[] eachStu;
eachStu = stu.split(" ");
students.add(new Student(eachStu[0], eachStu[1],
eachStu[2], Long.parseLong(eachStu[3]),
Integer.parseInt(eachStu[4]), Integer.parseInt(eachStu[5]),
Integer.parseInt(eachStu[6])));
} //end while
}//end try
//catch block for file not found exception
catch(FileNotFoundException fe) {
System.out.println("\nERROR: unable to open file.\n");
}//end of catch
//close file
readStudentFile.close();
}//end method

Solutions

Expert Solution

You can try this if you need to check perticular field

following class student,School, TestSchool are just for exmples ...

/*******************************Student.java************************/


/**
* @author
*
*/
public class Student {

   private String firstName;
   private String middleName;
   private String lastName;
   private long id;
   private int subMark1;
   private int subMark2;
   private int subMark3;

   public Student(String firstName, String middleName, String lastName, long id, int subMark1, int subMark2,
           int subMark3) {

       this.firstName = firstName;
       this.middleName = middleName;
       this.lastName = lastName;
       this.id = id;
       this.subMark1 = subMark1;
       this.subMark2 = subMark2;
       this.subMark3 = subMark3;
   }

   public String getFirstName() {
       return firstName;
   }

   public void setFirstName(String firstName) {
       this.firstName = firstName;
   }

   public String getMiddleName() {
       return middleName;
   }

   public void setMiddleName(String middleName) {
       this.middleName = middleName;
   }

   public String getLastName() {
       return lastName;
   }

   public void setLastName(String lastName) {
       this.lastName = lastName;
   }

   public long getId() {
       return id;
   }

   public void setId(long id) {
       this.id = id;
   }

   public int getSubMark1() {
       return subMark1;
   }

   public void setSubMark1(int subMark1) {
       this.subMark1 = subMark1;
   }

   public int getSubMark2() {
       return subMark2;
   }

   public void setSubMark2(int subMark2) {
       this.subMark2 = subMark2;
   }

   public int getSubMark3() {
       return subMark3;
   }

   public void setSubMark3(int subMark3) {
       this.subMark3 = subMark3;
   }

   @Override
   public String toString() {
       return "Name: " + firstName + " " + middleName + " " + lastName + "\nID: " + id + "\nMARKS: " + subMark1 + " "
               + subMark2 + " " + subMark3 + "\n";
   }

}
/*************************************School.java****************************/

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;

/**
* @author
*
*/
public class School {

   private ArrayList<Student> students;

   public School() {

       students = new ArrayList<Student>();
   }

   void readStudents() {
       // Scanner class object declare
       Scanner readStudentFile = null;
       // try block begin
       try {
           // open file
           readStudentFile = new Scanner(new File("student.txt"));
           // loop until end of file
           while (readStudentFile.hasNextLine()) {
               String stu = readStudentFile.nextLine();
               String[] eachStu;
               eachStu = stu.split(" ");

               String firstName = null, middleName = null, lastName = null;
               long id = 0;
               int mark1 = 0, mark2 = 0, mark3 = 0;
               /*
               * check for name is in correct format or not
               */
               try {

                   firstName = eachStu[0];
                   middleName = eachStu[1];
                   lastName = eachStu[2];
               } // catch block for invalid formatted line
               catch (NullPointerException e) {
                   System.out.println("Name is not correct!");
               }
               // check for id
               try {

                   id = Long.parseLong(eachStu[3]);
               } // catch block for invalid formatted line
               catch (NumberFormatException e) {
                   System.out.println("ID is not correct!");
               }
               // check for marks
               try {

                   mark1 = Integer.parseInt(eachStu[4]);
                   mark2 = Integer.parseInt(eachStu[5]);
                   mark3 = Integer.parseInt(eachStu[6]);
               } catch (NumberFormatException e) {

                   System.out.println("Subjects mark is not correct");
               }
               students.add(new Student(firstName, middleName, lastName, id, mark1, mark2, mark3));

           } // end while
           readStudentFile.close();// close file
       } // end try

       // catch block for file not found exception
       catch (FileNotFoundException fe) {
           System.out.println("\nERROR: unable to open file.\n");
       } // end of catch

   }// end method

   public void printStudents() {

       for (Student student : students) {

           System.out.println(student.toString());
       }
   }
}
/**********************************SchoolTest.java***********************/


/**
* @author
*
*/
public class TestSchool {

   public static void main(String[] args) {

       School school = new School();

       school.readStudents();
       school.printStudents();
   }
}
/************************student.txt**********************/

M S Dhoni 347564748 78 98 88
Virat Kohli 4356784574 44 57 88
R S Saini D33333 43 55 66
J K Sharma 3457956 F 65 44

/**********************output******************/

ID is not correct!
Subjects mark is not correct
Name: M S Dhoni
ID: 347564748
MARKS: 78 98 88

Name: Virat Kohli
ID: 4356784574
MARKS: 44 57 88

Name: R S Saini
ID: 0
MARKS: 43 55 66

Name: J K Sharma
ID: 3457956
MARKS: 0 0 0

Please let me know if you have any doubt or modify the answer, Thanks :)


Related Solutions

Create a class that calls for user to input a string. Pass the string from that...
Create a class that calls for user to input a string. Pass the string from that class to another and count how many words the string has, count how many vowels are in the string and count how many letters end with d. java language
Your code needs to do the following: Create a function called pigLatin that accepts a string...
Your code needs to do the following: Create a function called pigLatin that accepts a string of English words in the parameter sentence and returns a string of those words translated into Pig Latin. English is translated to Pig Latin by taking the first letter of every word, moving it to the end of the word and adding ‘ay’. For example the sentence “The quick brown fox” becomes “hetay uickqay rownbay oxfay”. You may assume the words in the parameter...
In Python Create a function called ????. The function receives a "string" that represents a year...
In Python Create a function called ????. The function receives a "string" that represents a year (the variable with this "String" will be called uve) and a list containing "strings" representing bank accounts (call this list ????). • Each account is represented by 8 characters. The format of each account number is "** - ** - **", where the asterisks are replaced by numeric characters. o For example, “59-04-23”. • The two central characters of the "string" of each account...
Function 6: Sorting string function name (str) a. This function receives an string. Your task is...
Function 6: Sorting string function name (str) a. This function receives an string. Your task is loop through the each character of the string and separate all digists/letters/special characters. Display all digits at the beginning, followed by letters then the special chars and display result in console. For example if following string is passed to this function “ha1m2i3:n)” Result should be: 123hamin:)
I'm trying to create a function determines the range of outliers in an array using pass...
I'm trying to create a function determines the range of outliers in an array using pass by reference. I need to write a function that outputs the +3 and -3 standard deviation. I'm having a hard time figuring out what I should identify as my pointers and how to use the pass by reference. This is what I have so far: #include <stdio.h> #define ARRAY_SIZE 20 double homeworkArray[ARRAY_SIZE] = { 1.3, 5.7, 2.1, -1.2, 0.5, 4.3, 2.1, 50.2, 3.4, 1.1,...
PYTHON 3: must use try/except for exception handling Write a function extractInt() that takes a string...
PYTHON 3: must use try/except for exception handling Write a function extractInt() that takes a string as a parameter and returns an integer constructed out of the digits that appear in the string. The digits in the integer should appear in the same order as the digits in the string. If the string does not contain any digits or an empty string is provided as a parameter, the value 0 should be return.
Matlab Create/write a function that takes an input of x and y data, and a string...
Matlab Create/write a function that takes an input of x and y data, and a string (either linear? or quadratic), sets up a linear system of equations (Ax = b), and solves and plots the model.
Python create a function tryhard and print out the dictionary as a string form. For example...
Python create a function tryhard and print out the dictionary as a string form. For example def tryhard(d:dict): #Code here input: d = {'first': {}, 'second': {'1': {'move'}, '0': {'move', 'slow'}}, 'third': {'1': {'stop'}}} output = " first movie: [ ]\n third movie: [('1', ['stop'])]\n second movie: [('0', ['slow', 'move']), ('1', ['move'])]\n"
Create a function called time2Greeting. It takes a time (in military time) and returns a string...
Create a function called time2Greeting. It takes a time (in military time) and returns a string with the right greeting. Good Morning 4AM to before noon. Good Afternoon Noon to before 5PM Good Evening from 5PM to 11PM What are you doing up at this hour? between 11 and 4AM For illegal values, say: That is not a valid time. Example: What is your name?   John What time is it? 1315 Good afternoon, John. C++ programming
Using the Iris dataset in R; PLEASE CREATE YOUR OWN FUNCTION USING FORMULAS INTEAD OF FUNCTIONS...
Using the Iris dataset in R; PLEASE CREATE YOUR OWN FUNCTION USING FORMULAS INTEAD OF FUNCTIONS THAT ARE BUILT IN R ,,,,,PLEASE TRY PLEASE a Carry out a hypothesis to test if the population sepal length mean is 6.2 at α = 0.05. Interpret your results. b Carry out a hypothesis to test if the population sepal width mean is 4 at α = 0.05. Interpret your results. c Carry out a hypothesis to test if the population sepal width...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT