How can I change the code to handle the absence of the "animal.txt" file without printing an error message?

What I do need help with is only that error that says Error: The file ‘animal.txt’ does not exist.

I made sure and even verified with chatgpt the rest of the code follows those requirements so you don’t have to worry about fixing that part (at least what it seems to be). What I do need help with is how to implement the animal.txt file in the code without it generating that error.

I hope this makes sense cause looking back at the other messages, it didn’t explain enough

Try copy out the code to and try debug it too. I forgot to make that clear.

If you want that error to not exist, you can delete it from the code.

What do you expect the code to do if that file doesn’t exist, though?

Here is the hard part and the reason I am asking this. If I delete the animal.txt file part of the code, then it would cause more errors + deviate from the instructions.

How about we try fix line 10 of the code?
System.err.println(“Error: The file ‘animal.txt’ does not exist.”);

But try copy and paste that code yourself and try see the problems with it.

I actually have a code that solves the animal.txt file error but it spawns something different

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class ProgThree {
public static void main(String args) {
File inputFile = new File(“data/animal.txt”);
if (!inputFile.exists()) {
try {
inputFile.createNewFile();
System.out.println(“Created file: animal.txt”);
} catch (IOException e) {
System.err.println(“Error: Failed to create the file ‘animal.txt’.”);
e.printStackTrace();
return;
}
}

    try {
        Scanner scanner = new Scanner(inputFile);
        PrintWriter writer = new PrintWriter("animalout.txt");
        int animalsCount = 0, petsCount = 0, zooAnimalsCount = 0;
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            String[] data = line.split(" ");
            if (data.length == 3) { // Animal
                int id = Integer.parseInt(data[0]);
                String type = data[1];
                double weight = Double.parseDouble(data[2]);
                if (isValidAnimal(id, type, weight)) {
                    Animal animal = new Animal(id, type, weight);
                    writer.println(animal);
                    animalsCount++;
                }
            } else if (data.length == 5) { // Pet or ZooAnimal
                int id = Integer.parseInt(data[0]);
                String type = data[1];
                double weight = Double.parseDouble(data[2]);
                if (id >= 3000 && id <= 7999 && isValidPet(id, type, weight, data[3], data[4])) {
                    Pet pet = new Pet(id, type, weight, data[3], data[4]);
                    writer.println(pet);
                    petsCount++;
                } else if (id >= 8000 && id <= 9999) {
                    if (isValidZooAnimal(id, type, weight, data[3], data[4])) {
                        ZooAnimal zooAnimal = new ZooAnimal(id, type, weight, Integer.parseInt(data[3]), data[4]);
                        writer.println(zooAnimal);
                        zooAnimalsCount++;
                    }
                }
            }
        }
        writer.println("Total Animals: " + animalsCount);
        writer.println("Total Pets: " + petsCount);
        writer.println("Total Zoo Animals: " + zooAnimalsCount);
        scanner.close();
        writer.close();
    } catch (FileNotFoundException e) {
        System.err.println("Error: The file 'animal.txt' was not found.");
        e.printStackTrace();
    }
}

private static boolean isValidAnimal(int id, String type, double weight) {
    return id >= 1000 && id <= 2999 && type.length() >= 3 && weight > 0;
}

private static boolean isValidPet(int id, String type, double weight, String name, String owner) {
    return id >= 3000 && id <= 7999 && type.length() >= 3 && weight > 0 && name.length() >= 3 && owner.length() >= 3;
}

private static boolean isValidZooAnimal(int id, String type, double weight, String cageNumber, String trainer) {
    try {
        int cageNum = Integer.parseInt(cageNumber);
        return id >= 8000 && id <= 9999 && type.length() >= 3 && weight > 0 && cageNum > 0 && trainer.length() >= 3;
    } catch (NumberFormatException e) {
        return false;
    }
}

}

class Animal {
private int id;
private String type;
private double weight;

public Animal(int id, String type, double weight) {
    this.id = id;
    this.type = type;
    this.weight = weight;
}

public int getId() {
    return id;
}

public String getType() {
    return type;
}

public double getWeight() {
    return weight;
}

@Override
public String toString() {
    return "Animal{" +
           "id=" + id +
           ", type='" + type + '\'' +
           ", weight=" + weight +
           '}';
}

}

class Pet extends Animal {
private String name;
private String owner;

public Pet(int id, String type, double weight, String name, String owner) {
    super(id, type, weight);
    this.name = name;
    this.owner = owner;
}

@Override
public String toString() {
    return "Pet{" +
           "id=" + getId() +
           ", type='" + getType() + '\'' +
           ", weight=" + getWeight() +
           ", name='" + name + '\'' +
           ", owner='" + owner + '\'' +
           '}';
}

}

class ZooAnimal extends Animal {
private int cageNumber;
private String trainer;

public ZooAnimal(int id, String type, double weight, int cageNumber, String trainer) {
    super(id, type, weight);
    this.cageNumber = cageNumber;
    this.trainer = trainer;
}

@Override
public String toString() {
    return "ZooAnimal{" +
           "id=" + getId() +
           ", type='" + getType() + '\'' +
           ", weight=" + getWeight() +
           ", cageNumber=" + cageNumber +
           ", trainer='" + trainer + '\'' +
           '}';
}

}

java -cp /tmp/Io2IdU6U98/ProgThree
ERROR!
Error: Failed to create the file ‘animal.txt’.
java.io.IOException: No such file or directory
at java.base/java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.base/java.io.File.createNewFile(File.java:1035)
at ProgThree.main(ProgThree.java:12)

  1. Do you understand what the code is doing?
  2. Do you understand why it is throwing that error?
  3. What do you want that code to do differently in that situation?
2 Likes

I do understand what the code is supposed to be doing.

I am confused on why it is throwing that error.

Question 3, you can modify the code to fix that error but don’t change it entirely. I don’t if the code is fixed by either modifying it or adding a folder.

  1. Do you see where in the code it prints that line?
  2. Do you see the if statement which must be true for it to print that line?
  3. It prints that line because the condition is true!
  4. You understand the code, right? So you understand that conditional and why/when it would be true. So you should understand when and why it prints that line.

Which of the above exactly are you unsure about?

I certainly can! I can change the message or delete it. But so can you! If you understand what prints that message, you can delete that line of code.

Its pretty hard to add a folder to code … but pretty easy to do on your computer!

1 Like