Профессор получает исключение java.io.FileNotFoundException, а я нет? - PullRequest
0 голосов
/ 27 апреля 2018

У меня был проект для моего класса Java, где пользователь вводит пациентов в больницу, затем программа читает файл, и пользователь может выбрать для добавления добавленных пациентов в файл, распечатать его на экране или и то, и другое. Программа отлично работает в NetBeans для меня, но в комментариях профессора он говорит, что его компилятор получил исключение FileNotFoundException (Edit: это на самом деле ошибка времени выполнения), хотя я включил файл в пакет. Когда я отправил ему электронное письмо, он только повторил, что получил исключение FileNotFoundException. Вот код:

    package realworldproblem3;


import java.util.*;
import java.io.*;
public class xyzHospital {

static int numOfPat;
static Scanner input = new Scanner(System.in);
static String inp;
static ArrayList<Patient> p = new ArrayList<>();

public static void main(String[] args) throws IOException {  
   boolean done = false;

           importPatients();
           System.out.print("Add new patients to the report:\n");
           while (done == false){
               addPatient();
               System.out.print("Are you done adding patients? (Y or N)\n");
               inp = input.nextLine();
               switch (inp.toLowerCase()){
                   case "y": done = true;
                   break;
                   case "n": done = false;
                   break;
                   default: System.out.print("You did not enter a valid character. The program will print results then exit.\n\n");
                   done = true;
                   break;
               }

           }
           printAll();

       }






static public void addPatient(){
     numOfPat++;
     Patient pat = new Patient();
     p.add(pat);
     pat.addInfo(numOfPat);
 }

static public void printAll() throws IOException{
    System.out.print("Do you want to output the report to the screen ('S'), to a file ('F'), or both('B')?\n");
    inp = input.next();
    PrintWriter writer = new PrintWriter("XYZHospitalExampleData-1.txt");
    switch (inp.toLowerCase()){
        case "s":
             System.out.print("\t\t\t\t\tXYZ Community Hospital\t\t\n=============================================================================================================\n");
             System.out.printf("%-14s%30s%38s%n", "    Name", "Address", "Payment Information");
             System.out.printf("%-8s%-8s%15s%10s%10s%8s%15s%15s%15s %n", "Last", "First", "Address Line 1", "City", "State", "Zip", "Payment Date", "Payment Amt.","Amount Owed");
             System.out.print("=============================================================================================================\n");
            for(int i = 0; i<numOfPat;i++){
                p.get(i).print();
            }
            break;

        case "f": 
            writer.print(""); //writes over file so there is no duplicate patients
            writer.close();
            for(int i = 0; i<numOfPat;i++){
                p.get(i).printToFile();
            }
            break;

        case "b":
             System.out.print("\t\t\t\t\tXYZ Community Hospital\t\t\n=============================================================================================================\n");
             System.out.printf("%-14s%30s%38s%n", "    Name", "Address", "Payment Information");
             System.out.printf("%-8s%-8s%15s%10s%10s%8s%15s%15s%15s %n", "Last", "First", "Address Line 1", "City", "State", "Zip", "Payment Date", "Payment Amt.","Amount Owed");
             System.out.print("=============================================================================================================\n");
            writer.print("");
            writer.close();
            for(int i = 0; i<numOfPat;i++){
                p.get(i).printToFile();
                p.get(i).print();
            }
            break;
}
}

//each patient from the file is added as a patient object
 static public void importPatients() throws IOException{
     try(Scanner read = new Scanner(new BufferedReader(new FileReader("XYZHospitalExampleData-1.txt")))) {
          while(read.hasNextLine()){ //one more line means that there is another patient to add
                    numOfPat++;
                    read.nextLine();
         }

          read.close();

          try(Scanner r = new Scanner(new BufferedReader(new FileReader("XYZHospitalExampleData-1.txt")))) {
                    for (int j=0; j < numOfPat; j++){

                        String line = r.nextLine();
                        Patient pat = new Patient();
                        p.add(pat);
                        String[] str = line.split("\\^"); //the delimiter ^ is used to separate information in the file

                        for (int i = 0; i < str.length; i++){
                            if(str[i].isEmpty()||str[i].matches("0")||str[i] == null){ //if str[i] is empty, that means that it will be skipped over
                                i++;
                            }
                            switch (i){
                                case 0: p.get(j).ID = Integer.parseInt(str[i]);
                                break;
                                case 1: p.get(j).nameLast = str[i];
                                break;
                                case 2: p.get(j).nameFirst = str[i];
                                break;
                                case 3: p.get(j).address = str[i];
                                break;
                                case 4: p.get(j).opAddr = str[i];
                                break;
                                case 5: p.get(j).city = str[i];
                                break;
                                case 6: p.get(j).state = str[i];
                                break;
                                case 7: p.get(j).zip = Integer.parseInt(str[i]);
                                break;
                                case 8: p.get(j).optZip = Integer.parseInt(str[i]);
                                break;
                                case 9: p.get(j).payDate = str[i];
                                break;
                                case 10: p.get(j).payment = Double.parseDouble(str[i]);
                                break;
                                case 11: p.get(j).owed = Double.parseDouble(str[i]);
                                break;
                                default: System.out.print("Error.\n");
                                break;
                            }
                      }
                    }
                    r.close(); 
                   }
            }
 }
}

Вот класс пациентов:

package realworldproblem3;
import java.util.*;
import java.io.*;


public class Patient {
Scanner input = new Scanner(System.in);
 String nameFirst, nameLast, address, opAddr,city, state, payDate;
 int zip, optZip, ID;
 double owed, payment;


 public void print() {
    System.out.printf("%-8s%-9s%-20s%-10s%-8s%-7s%-15s%-11.2f%-10.2f%n", nameLast, nameFirst, address, city, state, zip, payDate, owed, payment);
 }

 public void printToFile()throws IOException{
    try (PrintWriter writer = new PrintWriter(new FileWriter("XYZHospitalExampleData-1.txt", true))) {
        writer.write(ID + "^" + nameLast+ "^" + nameFirst + "^" + address + "^" + opAddr + "^" + city + "^" + state + "^" + zip + "^" + optZip + "^"+  payDate  + "^" + payment + "^" + owed +"\n");
        writer.close();
    }
 }
 private void setName(){
   System.out.print("Enter patient's first name.\n"); //user is asked for all information
    nameFirst = input.nextLine();                       //first three inputs use nextLine so it consumes the end of line character, so the address will be put in the string correctly.
     System.out.print("Enter patient's last name.\n");  //if next() is used, the address is cut off at the first whitespace and the other elements of the address
    nameLast = input.nextLine();                                //are stored in the upcoming inputs.
    if (nameFirst.isEmpty()||nameLast.isEmpty()){
        System.out.print("You must enter the first and last name.\n");
        setName();
    }
 }
 public String getName(){
     return nameFirst + " " + nameLast;
 }

 private void setAddr(){
      System.out.print("Enter patient's address.\n");
    address = input.nextLine();
    if (address.isEmpty()){
        System.out.print("You must enter the patients address.\n");
        setAddr();
    }
 }
 public String getAddr(){
     return address;
 }

 private void setCity(){
     System.out.print("Enter patient's home city.\n");
    city = input.nextLine();
    if(city.isEmpty()){
        System.out.print("You must enter the patients city.\n");
        setCity();
    }
 }
 public String getCity(){
     return city;
 }

 private void setState(){
      System.out.print("Enter patient's state.\n");
    state = input.nextLine();
    if(state.isEmpty()){
        System.out.print("You must enter the patients state.\n");
        setState();
    }
 }
 public String getState(){
     return state;
 }

 private void setDate(){
      System.out.print("Enter the payment date.\n");
    payDate = input.next();
    if(payDate.isEmpty()){
        System.out.print("You must enter a payment date.\n");
        setDate();
    }
 }
 public String getDate(){
     return payDate;
 }

 private void setZip(){
     System.out.print("Enter patient's zipcode.\n");
    try{
        zip = input.nextInt();
    }
    catch(Exception e){
        System.out.print("You must enter a valid 5-digit zipcode.\n");
        input.next();
        setZip();  //if it says that the setZip call will make the function loop infinitely, it is just a warning, it will not loop infinitely.
    }
    int length = String.valueOf(zip).length();
    if(length != 5 && zip > 0){
      System.out.print("You must enter a valid 5-digit zipcode.\n");
      setZip();        
    }

 }
 public int getZip(){
     return zip;
 }

 private void setOwed(){
     System.out.print("Enter patient's due balance.\n");
    try{
        owed = input.nextDouble();
    }
    catch(Exception e){
        System.out.print("Amount has to be a non-negative number.\n");
        input.next();
        setOwed();
    }
    int length = String.valueOf(owed).length();
    if (owed <0 || length == 0){
        System.out.print("Amount has to be a non-negative number.\n");
        setOwed();
    }
 }
 public double getOwed(){
     return owed;
 }

 private void setPayment(){
      System.out.print("Enter patient's payment amount.\n");
    try{
        payment = input.nextDouble();
    }
    catch(Exception e){
         System.out.print("Payment amount has to be a positive number less than the amount owed.\n");
         input.next();
        setPayment();
    }
    int length = String.valueOf(payment).length();
    if(payment < 0 || length ==0 || payment > owed){
        System.out.print("Payment amount has to be a positive number less than the amount owed.\n");
        setPayment();
    }
 }
 public double getPayment(){
     return payment;
 }

 private void setID(int Id){
     ID = Id;
 }
 public int getID(){
     return ID;
 }

 public void addInfo(int ID){
     setID(ID);
     setName();
     setAddr();
     setCity();
     setState();
     setZip();
     setOwed();
     setPayment();
     setDate();
 }


}

А вот и файл XYZHospitalExampleData-1.txt:

12345 ^ Джонс ^ Джон ^ 1234 Тест-драйв ^ PO box 123 ^ Тест-город ^ IN ^ 11234 ^ 1234 ^ 12/05/2015 ^ 250,0 ^ 25000,0 12346 ^ Джонс ^ Сара ^ 1234 Тест-драйв ^ PO box 123 ^ Тест-город ^ IN ^ 11234 ^ 1234 ^ 12/20 / 2017 ^ 50.0 ^ 50000.0 12347 ^ Доу ^ Джон ^ 1235 XYZ Drive ^ ноль ^ Тестовый город ^ IN ^ 11234 ^ 0 ^ 01/05/2016 ^ 350.0 ^ 56799.0 12348 ^ Доу ^ Сара ^ 1235 XYZ Drive ^ ноль ^ Тестовый город ^ IN ^ 11234 ^ 0 ^ 11/09/2017 ^ 100.0 ^ 5020.52 12349 ^ Лоусон ^ Лонни ^ 12 Саут Драйв ^ ноль ^ Тестовый город ^ IN ^ 11236 ^ 0 ^ 03/15/2013 ^ 253.51 ^ 25065.52 12349 ^ Андерсон ^ Сара ^ 156 Северный проспект ^ ноль ^ Тестовый город ^ IN ^ 11246 ^ 0 ^ 05/05/2013 ^ 21,33 ^ 251,56 12350 ^ Смит ^ Энди ^ 2455 Ист-стрит ^ ноль ^ Тестовый город ^ IN ^ 11246 ^ 0 ^ 12/05/2017 ^ 365.21 ^ 2543.33

Он начинается с их идентификатора и заканчивается суммой, которую они должны. Буду признателен за любую помощь, чтобы понять, почему компилятор моего профессора дает ему ошибку, и что я могу сделать, чтобы быть уверенным, что он сможет найти файл, чтобы у меня больше не возникало этой проблемы.

1 Ответ

0 голосов
/ 27 апреля 2018

В начале вашего main метода вы вызываете importPatients, который считывает данные из файла XYZHospitalExampleData-1.txt. Если этот файл отсутствует, вы получите исключение (во время выполнения, а не ошибка компилятора).

Скорее всего, что-то пошло не так, когда ваш пакет был распакован. Возможно, файл не был скопирован в ожидаемое место, что-то в этом роде. Одним из способов решения этой проблемы было бы перехватить FileNotFoundException и отобразить сообщение, описывающее, что пошло не так и что ожидается.

...