Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Why it isnt adding the ins and deleting the outs? HELP

  1. #1
    Junior Member
    Join Date
    Apr 2024
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Why it isnt adding the ins and deleting the outs? HELP

    SORRY, for some reason i cannot attach files :-(


    this should read the files, process the I/O and create file2.txt such as:
    7;5;3
    0:0:0;PSX123
    0:2:0;PAA111
    1:4:1;DBB222
    3:0:0;HCC333

    but instead generates this:

    7;5;3
    0:0:0;PSX123
    1:0:0;DTB246
    0:2:0;PAA111
    1:4:1;DBB222



    package p3;

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;

    public class p3 {
    // Arrays to store pets
    private static Parrot[] parrots = new Parrot[25];
    private static Dog[] dogs = new Dog[25];
    private static HuntingDog[] huntDogs = new HuntingDog[25];

    public static void main(String[] args) {
    Residence myResidence = null;

    if (args.length != 4) {
    System.out.println("Correct execution: java p3 <file0> <file1> <file2> <file3>");
    return;
    }

    try {
    readPetsFile(args[3]);
    myResidence = new Residence(args[0]);
    processIO(myResidence, args[1]);
    myResidence.saveResidenceToFile(args[2]);
    int totalSpending = computeTotalSpending();
    System.out.println("Total spent by all pets = " + totalSpending);
    increaseHuntingDogsWeight(0.10f);
    writeHuntingDogsFile("huntDogs_output.txt");
    HuntingDog huntingDog = new HuntingDog("XYZ123", "Rex", 25.0f, 1000, 'Y', 'R');
    System.out.println("Original Weight: " + huntingDog.getWeight());
    huntingDog.addWeight(huntingDog.getWeight() * 0.10f);
    System.out.println("Updated Weight: " + huntingDog.getWeight());
    } catch (Exception e) {
    e.printStackTrace();
    }

    /* saveResidenceMap("ResidenceMap_output.txt", myResidence); */
    }

    // Method to read pet data from pets.txt and create objects
    public static void readPetsFile(String filename) {
    try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
    String line;
    while ((line = reader.readLine()) != null) {
    String[] petData = line.split(";");
    if (petData.length >= 6) {
    String type = petData[0];
    String id = petData[1];
    String name = petData[2];
    float weight = Float.parseFloat(petData[3].replace(",", "."));
    int spending = Integer.parseInt(petData[4].replaceAll("[^\\d.]", ""));

    switch (type) {
    case "P":
    short speakCapability = Short.parseShort(petData[5]);
    Parrot parrot = new Parrot(id, name, weight, spending, speakCapability);
    addPet(parrot, parrots);
    break;
    case "D":
    char dangerous = petData[5].charAt(0);
    Dog dog = new Dog(id, name, weight, spending, dangerous);
    addPet(dog, dogs);
    break;
    case "H":
    dangerous = petData[5].charAt(0);
    char prey = petData[6].charAt(0);
    HuntingDog huntDog = new HuntingDog(id, name, weight, spending, dangerous, prey);
    addPet(huntDog, huntDogs);
    break;
    }
    }
    }
    } catch (IOException | NumberFormatException e) {
    e.printStackTrace();
    }
    }

    // Method to add pet to the appropriate array
    private static <T extends Pet> void addPet(T pet, T[] petArray) {
    for (int i = 0; i < petArray.length; i++) {
    if (petArray[i] == null) {
    petArray[i] = pet;
    break;
    }
    }
    }

    // Method to compute total spending across all pets
    public static int computeTotalSpending() {
    int totalSpending = 0;
    for (Parrot parrot : parrots) {
    if (parrot != null) {
    totalSpending += parrot.getSpending();
    }
    }
    for (Dog dog : dogs) {
    if (dog != null) {
    totalSpending += dog.getSpending();
    }
    }
    for (HuntingDog huntDog : huntDogs) {
    if (huntDog != null) {
    totalSpending += huntDog.getSpending();
    }
    }
    return totalSpending;
    }

    // Method to increase the weight of all hunting dogs
    public static void increaseHuntingDogsWeight(float incr) {
    for (HuntingDog huntDog : huntDogs) {
    if (huntDog != null) {
    float extraWeight = huntDog.getWeight() * incr;
    huntDog.addWeight(extraWeight);
    }
    }
    }

    // Method to write updated hunting dog data to huntDogs_output.txt
    public static void writeHuntingDogsFile(String filename) {
    try (FileWriter writer = new FileWriter(filename)) {
    for (HuntingDog huntDog : huntDogs) {
    if (huntDog != null) {
    writer.write(huntDog.toString() + "\n");
    }
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    // Method to process Ins and Outs

    public static void processIO(Residence aResidence, String fileName) {
    List<String> checkInOperations = new ArrayList<>();
    List<String> checkOutOperations = new ArrayList<>();

    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
    String line;

    // First, separate check-in and check-out operations
    while ((line = reader.readLine()) != null) {
    if (line.startsWith("#") || line.trim().isEmpty()) {
    continue; // Ignore comments and empty lines
    }

    String[] parts = line.split(";");
    if (parts.length >= 3) {
    String typeIO = parts[0];
    String id = parts[1];
    char petType = parts[2].charAt(0);

    if (typeIO.equals("I")) {
    checkInOperations.add(line);
    } else if (typeIO.equals("O")) {
    checkOutOperations.add(line);
    }
    }
    }

    // Process check-out operations first
    for (String operation : checkOutOperations) {
    String[] parts = operation.split(";");
    if (parts.length >= 3) {
    String id = parts[1];
    aResidence.petOut(id);
    }
    }

    // Process check-in operations after all check-outs are done
    for (String operation : checkInOperations) {
    String[] parts = operation.split(";");
    if (parts.length >= 3) {
    String id = parts[1];
    char petType = parts[2].charAt(0);
    if (petType == 'H') {
    // Add Hunting dog to residence
    aResidence.petIn(id, petType);
    } else {
    // For other pet types, add directly
    aResidence.petIn(id, petType);
    }
    }
    }
    } catch (IOException e) {
    e.printStackTrace();
    }

    // After processing IO, save the updated residence to file2
    aResidence.saveResidenceToFile("file2.txt");
    }


    }

    package p3;

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.HashSet;
    import java.util.Set;


    public class Residence {
    private short sizeLanes;
    private short sizeNums;
    private short sizeLevels;
    private short minHuntDogLane;
    private Place[][][] places;
    private Set<String> residentPets; // Store IDs of resident pets
    private String fileName;
    private Set<String> writtenIds;
    private Set<String> processedResidentPets;

    public Residence(String fileName) throws IOException {
    writtenIds = new HashSet<>();
    this.fileName = fileName;
    residentPets = new HashSet<>();
    processedResidentPets = new HashSet<>();

    try(BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
    String line;
    boolean firstLineProcessed = false;

    while((line = reader.readLine()) != null) {
    if (line.startsWith("#")) {
    continue;
    }

    if (!firstLineProcessed) {
    processFirstLine(line);
    places = new Place[sizeLanes][sizeNums][sizeLevels];
    initializePlaces();
    minHuntDogLane = sizeLanes;
    firstLineProcessed = true;
    } else {
    processOccupiedPlace(line);
    }
    }
    }
    }

    private void processFirstLine(String line) {
    String[] dimensions = line.split(";");

    if (dimensions.length != 3) {
    System.err.println("Error: Unexpected input in first line.");
    return;
    }

    try {
    sizeLanes = Short.parseShort(dimensions[0]);
    sizeNums = Short.parseShort(dimensions[1]);
    sizeLevels = Short.parseShort(dimensions[2]);
    } catch (NumberFormatException e) {
    System.err.println("Error: unable to parse dimensions from the first line.");
    e.printStackTrace();
    }
    }

    private void processOccupiedPlace(String line) {
    String[] parts = line.split(";");

    if (parts.length == 2) {
    String id = parts[1].trim();

    // Check if the ID has already been processed during initialization
    if (processedResidentPets.contains(id)) {
    return; // Skip processing if the ID has already been processed
    }

    String[] locationParts = parts[0].split(":");

    if (locationParts.length == 3) {
    short lane = Short.parseShort(locationParts[0].trim());
    short num = Short.parseShort(locationParts[1].trim());
    short level = Short.parseShort(locationParts[2].trim());

    if (lane >= 0 && lane < sizeLanes && num >= 0 && num < sizeNums && level >= 0 && level < sizeLevels) {
    if (places[lane][num][level].getIdPet() == null) { // Check if the place is unoccupied
    places[lane][num][level].setIdPet(id);
    // Add the ID to the set of written IDs
    writtenIds.add(id);
    // Write the ID to the file
    writePetToFile(String.format("%d:%d:%d;%s\n", lane, num, level, id));
    }
    // Add the ID to the set of processed resident pets
    processedResidentPets.add(id);
    } else {
    System.err.println("Error, invalid loc for occupied place: " + line);
    }
    } else {
    System.err.println("Error: invalid format for occupied place: " + line);
    }
    } else {
    System.err.println("Error: invalid format for occupied place: " + line);
    }
    }

    private void writePetToFile(String petInfo) {
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true))) {
    writer.write(petInfo);
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    private void initializePlaces() {
    for(short lane = 0; lane < sizeLanes; lane++) {
    for (short num = 0; num < sizeNums; num++) {
    for (short level = 0; level < sizeLevels; level++) {
    places[lane][num][level] = new Place(new PlaceLocator(lane, num, level), null);
    }
    }
    }
    }

    public static Residence createResidenceFromFile(String fileName) throws IOException {
    Residence residence = null;

    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
    String line;
    boolean firstLineProcessed = false;

    while ((line = reader.readLine()) != null) {
    if (line.startsWith("#") || line.trim().isEmpty()) {
    continue; // Skip comments and empty lines
    }

    if (!firstLineProcessed) {
    String[] dimensions = line.split(";");
    if (dimensions.length != 3) {
    throw new IOException("Invalid format in first line of the file.");
    }
    short sizeLanes = Short.parseShort(dimensions[0].trim());
    short sizeNums = Short.parseShort(dimensions[1].trim());
    short minHuntDogLane = Short.parseShort(dimensions[2].trim());
    residence = new Residence(fileName);
    residence.setSizeLanes(sizeLanes);
    residence.setSizeNums(sizeNums);
    residence.setMinHuntDogLane(minHuntDogLane);
    firstLineProcessed = true;
    } else {
    residence.processOccupiedPlace(line);
    }
    }
    }

    if (residence == null) {
    throw new IOException("No valid data found in the file.");
    }

    return residence;
    }

    private void setMinHuntDogLane(short minHuntDogLane) {
    this.minHuntDogLane = minHuntDogLane;
    }

    private void setSizeNums(short sizeNums) {
    this.sizeNums = sizeNums;
    }

    private void setSizeLanes(short sizeLanes) {
    this.sizeLanes = sizeLanes;
    }

    public void saveResidenceToFile(String fileName) {
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
    // Write the dimensions of the Residence as the first line
    writer.write(String.format("%d;%d;%d\n", sizeLanes, sizeNums, sizeLevels));

    // Iterate over the places and write occupied ones in the specified order
    for (short level = 0; level < sizeLevels; level++) {
    for (short num = 0; num < sizeNums; num++) {
    for (short lane = 0; lane < sizeLanes; lane++) {
    Place place = places[lane][num][level];
    if (place != null && place.getIdPet() != null) {
    // Write the occupied place to the file
    writer.write(String.format("%d:%d:%d;%s\n", lane, num, level, place.getIdPet()));
    }
    }
    }
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    public void petIn(String id, char petType) {
    short sizeLanes = getSizeLanes();
    short sizeNums = getSizeNums();
    short sizeLevels = getSizeLevels();
    Place[][][] places = getPlaces();

    // Determine the starting lane based on the pet type
    short startLane = 0;
    switch (petType) {
    case 'D':
    startLane = 1;
    break;
    case 'H':
    startLane = getMinHuntDogLane();
    break;
    // Parrots (P) can be placed in lanes starting at 0
    }

    // Iterate over lanes to find the first available place
    for (short lane = startLane; lane < sizeLanes; lane++) {
    for (short num = 0; num < sizeNums; num++) {
    for (short level = 0; level < sizeLevels; level++) {
    Place place = places[lane][num][level];
    if (place.getIdPet() == null) {
    // Found a free place, assign the pet to it
    place.setIdPet(id);
    return;
    }
    }
    }
    }
    }

    public void petOut(String id) {
    short sizeLanes = getSizeLanes();
    short sizeNums = getSizeNums();
    short sizeLevels = getSizeLevels();
    Place[][][] places = getPlaces();

    // Flag to track if the pet with the specified ID was found
    boolean petFound = false;

    // Iterate over all places to find the one occupied by the pet with the given id
    for (short lane = 0; lane < sizeLanes; lane++) {
    for (short num = 0; num < sizeNums; num++) {
    for (short level = 0; level < sizeLevels; level++) {
    Place place = places[lane][num][level];
    if (place.getIdPet() != null && place.getIdPet().equals(id)) {
    // Found the place occupied by the pet with the specified ID
    // Remove the pet by setting idPet to null
    place.setIdPet(null);
    petFound = true;
    break; // Exit the loop once the pet is removed
    }
    }
    if (petFound) {
    break; // Exit the loop once the pet is removed
    }
    }
    if (petFound) {
    break; // Exit the loop once the pet is removed
    }
    }

    // If the pet with the specified ID was not found, print an error message
    if (!petFound) {
    System.err.println("Error: Pet with ID " + id + " not found in the residence.");
    }
    }



    // GETTERS AND SETTERS
    public short getSizeLanes() {
    return sizeLanes;
    }

    public short getSizeNums() {
    return sizeNums;
    }

    public short getSizeLevels() {
    return sizeLevels;
    }

    public short getMinHuntDogLane() {
    return minHuntDogLane;
    }

    public Place[][][] getPlaces() {
    return places;
    }

    public String toMap(char sep) {
    int totalLanes = this.sizeLanes;
    int totalNumbers = this.sizeNums;
    int totalLevels = 2;

    // Calculate total rows and columns required for the map
    int totalRows = (totalLevels + 1) * totalLanes;
    int totalCols = (totalNumbers + 1) * totalLanes;

    // Create a StringBuilder to hold the graphical representation
    StringBuilder sb = new StringBuilder();

    // Iterate over the places in the Residence
    for (int lane = 0; lane < totalLanes; lane++) {
    for (int number = 0; number < totalNumbers; number++) {
    for (int level = totalLevels - 1; level >= 0; level--) {
    // Get the place from the Residence
    Place place = this.places[lane][number][level];

    // Append the pet information to the StringBuilder
    if (place != null && place.getIdPet() != null) {
    sb.append(sep);
    sb.append(lane);
    sb.append(':');
    sb.append(number);
    sb.append(':');
    sb.append(level);
    sb.append(' ');
    sb.append(place.getIdPet());
    } else {
    // If the place is free, append whitespace characters
    sb.append(" "); // 7 whitespace characters
    }
    }
    sb.append('\n');
    }
    sb.append("------------------------------------------------\n");
    }

    return sb.toString();
    }

    public String toMap() {
    return toMap('|');
    }

    public short[] chooseLocationForPet(char petType) {
    short[] location = new short[3]; // Array to store lane, number, and level

    // Determine the starting lane based on pet type
    short startLane;
    if (petType == 'H') {
    startLane = minHuntDogLane;
    } else if (petType == 'D') {
    startLane = 1; // Dogs can start from lane 1
    } else { // Parrots can start from lane 0
    startLane = 0;
    }

    // Iterate over lanes
    for (short lane = startLane; lane < sizeLanes; lane++) {
    // Iterate over numbers
    for (short num = 0; num < sizeNums; num++) {
    // Iterate over levels
    for (short lvl = 0; lvl < sizeLevels; lvl++) {
    // Check if the place is unoccupied
    if (places[lane][num][lvl].getIdPet() == null) {
    // Found an empty place, set the location and return
    location[0] = lane;
    location[1] = num;
    location[2] = lvl;
    return location;
    }
    }
    }
    }

    // If no available space found, return null
    return null;
    }

    }

    file0.txt:
    # 7 lanes, 5 numbers per lane. Lane 0 for parrots. Lanes 1 and 2 for dogs and parrots.
    7;5;3
    # hosted pets
    0:2:0;PAA111
    1:4:1;DBB222

    file1.txt:
    I;PSX123;P
    I;DTB246;D
    I;HCC333;H
    O;DTB246

    file3.txt:
    # pet list
    # parrots
    P;PAA111;Alexis;1,1;800;30
    P;PSX123;Coco;0,4;250;10
    # dogs
    D;DBB222;Pancho;5,3;1300;N
    D;DTB246;Bobby;6,5;895;N
    D;DTB431;Rob;7,3;1000;Y
    # hunting dogs
    H;HCC333;Rockie;12,6;999;Y;R
    H;HEA321;Thunder;21;600;Y;F
    # end of list



    //other files

    package p3;

    public class PlaceLocator {
    private short lane;
    private short num;
    private short level;

    // Constructors
    public PlaceLocator(short lane, short num, short level) {
    this.lane = lane;
    this.num = num;
    this.level = level;
    }

    // GET
    public short getLane() {
    return lane;
    }

    public short getNum() {
    return num;
    }

    public short getLevel() {
    return level;
    }

    // SET
    public void setLane(short lane) {
    this.lane = lane;
    }

    public void setNum(short num) {
    this.num = num;
    }

    public void setLevel(short level) {
    this.level = level;
    }

    // METHODS
    @Override
    public String toString() {
    return String.format("%d:%d:%d", lane, num, level);
    }

    @Override
    public boolean equals(Object obj) {
    if (this == obj) {
    return true;
    }
    if (obj == null || getClass() != obj.getClass()) {
    return false;
    }
    PlaceLocator other = (PlaceLocator) obj;
    return lane == other.lane && num == other.num && level == other.level;
    }
    }

    package p3;

    public class Place {

    private PlaceLocator placeLocator;
    private String idPet;

    // Constructor
    public Place(PlaceLocator placeLocator, String idPet) {
    this.placeLocator = placeLocator;
    this.idPet = idPet;
    }

    // GETTERS AND SETTERS
    public PlaceLocator getPlaceLocator() {
    return placeLocator;
    }

    public void setPlaceLocator(PlaceLocator placeLocator) {
    this.placeLocator = placeLocator;
    }

    public String getIdPet() {
    return idPet;
    }

    public void setIdPet(String idPet) {
    this.idPet = idPet;
    }

    // METHODS
    @Override
    public boolean equals(Object obj) {
    if (this == obj) {
    return true;
    }
    if (obj == null || getClass() != obj.getClass()) {
    return false;
    }
    Place other = (Place) obj;
    return placeLocator.equals(other.placeLocator);
    }

    @Override
    public String toString() {
    return (idPet != null) ? placeLocator.toString() + ";" + idPet : placeLocator.toString();
    }
    }


    package p3;

    public interface Pet {
    String getId();
    String getName();
    float getWeight();
    int getSpending();

    // You can include other common methods or attributes
    }

    package p3;

    public class Parrot implements Pet {

    // Instance attributes
    private String id;
    private String name;
    private float weight;
    private int spending;
    private short speakCapability;

    // Static attributes
    public static final String ID_FORMAT = "LLLDDD";
    public static final float MAX_WEIGHT = 100.0f;

    // Simple constructor
    public Parrot() {
    }

    // Argument constructor
    public Parrot(String id, String name, float weight, int spending, short speakCapability) {
    if (isValidId(id) && isValidName(name) && isValidWeight(weight) && isValidSpending(spending)
    && isValidSpeakCapability(speakCapability)) {

    this.id = id;
    this.name = name;
    this.weight = weight;
    this.spending = spending;
    this.speakCapability = speakCapability;

    } else {
    System.out.println("Cannot create a Parrot. \nError due to invalid parameters");
    }
    }

    // Methods
    public static boolean isValidId(String id) {
    return id.matches("[A-Z]{3}\\d{3}");
    }

    public static boolean isValidName(String name) {
    return name != null && name.matches("[A-Za-z]+");
    }

    public static boolean isValidWeight(float weight) {
    return weight > 0 && weight < MAX_WEIGHT;
    }

    public static boolean isValidSpending(int spending) {
    return spending >= 0;
    }

    public static boolean isValidSpeakCapability(short speakCapability) {
    return speakCapability >= 0 && speakCapability <= 60;
    }

    // Getters and Setters
    public String getId() {
    return id;
    }

    public void setId(String id) {
    if (isValidId(id)) {
    this.id = id;
    } else {
    System.out.println("Invalid format for ID.");
    }
    }

    public String getName() {
    return name;
    }

    public void setName(String Name) {
    if (isValidName(this.name)) {
    this.name = name;
    } else {
    System.out.println("Invalid format for Name.");
    }
    }

    public float getWeight() {
    return weight;
    }

    public void setWeight(float weight) {
    if (isValidWeight(weight)) {
    this.weight = weight;
    } else {
    System.out.println("Invalid format for Weight.");
    }
    }

    public int getSpending() {
    return spending;
    }

    public void setSpending(int spending) {
    if (isValidSpending(spending)) {
    this.spending = spending;
    } else {
    System.out.println("Invalid format for Money Spent.");
    }
    }

    public short getSpeakCapability() {
    return speakCapability;
    }

    public void setSpeakCapability(short speakCapability) {
    if (isValidSpeakCapability(speakCapability)) {
    this.speakCapability = speakCapability;
    } else {
    System.out.println("Invalid format for Speaking Capabilities.");
    }
    }

    public String toString() {
    return String.format("P;%s;%s;%.2f;%d;%d", id, name, weight, spending, speakCapability);
    }

    }


    package p3;

    public class HuntingDog implements Pet {

    // Instance attributes
    private String id;
    private String name;
    private float weight;
    private int spending;
    private char dangerous;
    private char prey;

    // Static attributes
    public static final String ID_FORMAT = "LLLDDD";
    public static final float MAX_WEIGHT = 100.0f;

    // Simple constructor
    public HuntingDog() {
    }

    // Argument constructor
    public HuntingDog(String id, String name, float weight, int spending, char dangerous, char prey) {
    if (isValidId(id) && isValidName(name) && isValidWeight(weight) && isValidSpending(spending)
    && isValidDangerous(dangerous) && isValidPrey(prey)) {

    this.id = id;
    this.name = name;
    this.weight = weight;
    this.spending = spending;
    this.dangerous = dangerous;
    this.prey = prey;

    } else {
    System.out.println("Cannot create a Hunting Dog. \nError due to invalid parameters");
    }
    }

    // Methods
    public static boolean isValidId(String id) {
    return id.matches("[A-Z]{3}\\d{3}");
    }

    public static boolean isValidName(String name) {
    return name != null && name.matches("[A-Za-z]+");
    }

    public static boolean isValidWeight(float weight) {
    return weight > 0 && weight < MAX_WEIGHT;
    }

    public static boolean isValidSpending(int spending) {
    return spending >= 0;
    }

    public static boolean isValidDangerous(char dangerous) {
    return dangerous == 'Y' || dangerous == 'N';
    }

    public static boolean isValidPrey(char prey) {
    return prey == 'P' || prey == 'R' || prey == 'F';
    }

    // Getters and Setters
    public String getId() {
    return id;
    }

    public void setId(String id) {
    if (isValidId(id)) {
    this.id = id;
    } else {
    System.out.println("Invalid format for ID.");
    }
    }

    public String getName() {
    return name;
    }

    public void setName(String Name) {
    if (isValidName(this.name)) {
    this.name = name;
    } else {
    System.out.println("Invalid format for Name.");
    }
    }

    public float getWeight() {
    return weight;
    }

    public void setWeight(float weight) {
    if (isValidWeight(weight)) {
    this.weight = weight;
    } else {
    System.out.println("Invalid format for Weight.");
    }
    }

    public int getSpending() {
    return spending;
    }

    public void setSpending(int spending) {
    if (isValidSpending(spending)) {
    this.spending = spending;
    } else {
    System.out.println("Invalid format for Money Spent.");
    }
    }

    public char getDangerous() {
    return dangerous;
    }

    public void setDangerous(char dangerous) {
    if (isValidDangerous(dangerous)) {
    this.dangerous = dangerous;
    } else {
    System.out.println("Invalid format for Dangerousness.");
    }
    }

    public char getPrey() {
    return prey;
    }

    public void setPrey(char prey) {
    if (isValidPrey(prey)) {
    this.prey = prey;
    } else {
    System.out.println("Invalid format for Prey.");
    }
    }

    public String toString() {
    return String.format("P;%s;%s;%.2f;%d;%c;%c", id, name, weight, spending, dangerous, prey);
    }

    public void addWeight(float extraWeight) {
    if (isValidWeight(weight + extraWeight)) {
    this.weight += extraWeight;
    } else {
    System.out.println("Invalid format for Weight.");
    }
    }

    }

    package p3;

    public class Dog implements Pet {

    // Instance attributes
    private String id;
    private String name;
    private float weight;
    private int spending;
    private char dangerous;

    // Static attributes
    public static final String ID_FORMAT = "LLLDDD";
    public static final float MAX_WEIGHT = 100.0f;

    // Simple constructor
    public Dog() {
    }

    // Argument constructor
    public Dog(String id, String name, float weight, int spending, char dangerous) {
    if (isValidId(id) && isValidName(name) && isValidWeight(weight) && isValidSpending(spending)
    && isValidDangerous(dangerous)) {

    this.id = id;
    this.name = name;
    this.weight = weight;
    this.spending = spending;
    this.dangerous = dangerous;

    } else {
    System.out.println("Cannot create a Dog. \nError due to invalid parameters");
    }
    }

    // Methods
    public static boolean isValidId(String id) {
    return id.matches("[A-Z]{3}\\d{3}");
    }

    public static boolean isValidName(String name) {
    return name != null && name.matches("[A-Za-z]+");
    }

    public static boolean isValidWeight(float weight) {
    return weight > 0 && weight < MAX_WEIGHT;
    }

    public static boolean isValidSpending(int spending) {
    return spending >= 0;
    }

    public static boolean isValidDangerous(char dangerous) {
    return dangerous == 'Y' || dangerous == 'N';
    }

    // Getters and Setters
    public String getId() {
    return id;
    }

    public void setId(String id) {
    if (isValidId(id)) {
    this.id = id;
    } else {
    System.out.println("Invalid format for ID.");
    }
    }

    public String getName() {
    return name;
    }

    public void setName(String Name) {
    if (isValidName(this.name)) {
    this.name = name;
    } else {
    System.out.println("Invalid format for Name.");
    }
    }

    public float getWeight() {
    return weight;
    }

    public void setWeight(float weight) {
    if (isValidWeight(weight)) {
    this.weight = weight;
    } else {
    System.out.println("Invalid format for Weight.");
    }
    }

    public int getSpending() {
    return spending;
    }

    public void setSpending(int spending) {
    if (isValidSpending(spending)) {
    this.spending = spending;
    } else {
    System.out.println("Invalid format for Money Spent.");
    }
    }

    public char getDangerous() {
    return dangerous;
    }

    public void setDangerous(char dangerous) {
    if (isValidDangerous(dangerous)) {
    this.dangerous = dangerous;
    } else {
    System.out.println("Invalid format for Dangerousness.");
    }
    }

    public String toString() {
    return String.format("P;%s;%s;%.2f;%d;%c", id, name, weight, spending, dangerous);
    }

    }
    Last edited by pablobardock; April 12th, 2024 at 10:50 AM. Reason: adding source files

  2. #2
    Member
    Join Date
    Jan 2024
    Posts
    75
    Thanks
    0
    Thanked 4 Times in 4 Posts

    Default Re: Why it isnt adding the ins and deleting the outs? HELP

    It seems like the issue lies in the `processIO` method where the check-out operations are processed before the check-in operations, resulting in unexpected behavior. To fix this, we need to ensure that check-out operations are processed after all check-in operations.

    Here's the corrected `processIO` method:

    ```java
    public static void processIO(Residence aResidence, String fileName) {
    List<String> checkInOperations = new ArrayList<>();
    List<String> checkOutOperations = new ArrayList<>();

    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
    String line;

    // First, separate check-in and check-out operations
    while ((line = reader.readLine()) != null) {
    if (line.startsWith("#") || line.trim().isEmpty()) {
    continue; // Ignore comments and empty lines
    }

    String[] parts = line.split(";");
    if (parts.length >= 3) {
    String typeIO = parts[0];
    String id = parts[1];
    char petType = parts[2].charAt(0);

    if (typeIO.equals("I")) {
    checkInOperations.add(line);
    } else if (typeIO.equals("O")) {
    checkOutOperations.add(line);
    }
    }
    }

    // Process check-in operations first
    for (String operation : checkInOperations) {
    String[] parts = operation.split(";");
    if (parts.length >= 3) {
    String id = parts[1];
    char petType = parts[2].charAt(0);
    if (petType == 'H') {
    // Add Hunting dog to residence
    aResidence.petIn(id, petType);
    } else {
    // For other pet types, add directly
    aResidence.petIn(id, petType);
    }
    }
    }

    // Process check-out operations after all check-ins are done
    for (String operation : checkOutOperations) {
    String[] parts = operation.split(";");
    if (parts.length >= 3) {
    String id = parts[1];
    aResidence.petOut(id);
    }
    }
    } catch (IOException e) {
    e.printStackTrace();
    }

    // After processing IO, save the updated residence to file2
    aResidence.saveResidenceToFile("file2.txt");
    }
    ```

    This modification ensures that check-in operations are processed before check-out operations, aligning with the intended logic of adding pets to the residence before removing them.

    After resolving the issues with the code logic, you might want to seek further assistance or guidance for your Java assignments. If you're looking for additional help with your Java assignment, there are various resources available online where you can find support and guidance. Whether it's through online forums, programming communities, or specialized platforms like ProgrammingHomworkHelp.com offering help with programming homework, you can explore different avenues to enhance your understanding and skills in Java programming.

Similar Threads

  1. Replies: 1
    Last Post: May 31st, 2013, 06:21 AM
  2. [SOLVED] database connection problem adding,deleting,updating,selecting :(
    By jabaman in forum What's Wrong With My Code?
    Replies: 13
    Last Post: December 6th, 2012, 01:05 PM
  3. JInternalFrame isnt working why
    By justyStepi in forum AWT / Java Swing
    Replies: 1
    Last Post: May 17th, 2012, 01:42 PM
  4. [SOLVED] Jframe Pop outs when clicking JButton
    By Java Programmer in forum What's Wrong With My Code?
    Replies: 7
    Last Post: January 22nd, 2012, 05:09 PM
  5. [Help] Problem with Class arrays, adding/editing and deleting
    By Grant_Searle in forum Object Oriented Programming
    Replies: 7
    Last Post: December 16th, 2011, 10:10 AM