brendalonian
brendalonian

Reputation: 11

How to set up if-else in Java to parse array elements

I am trying to set up my Java code to parse whether an element of my array attended either Disneyland or Universal studios. My array has 7 elements for 7 attendees. The attendees receive discounts specific to which park they attended, and I have created two for loops to represent the two parks.

How can I set up my code in the main method to determine which attendees went where?

public class Visitor
{
public static void main( String args[] ) 
{

  double totalAttendeeCost = 0.0;

  //Using 1 array
  VisitorPackage[] attendee = new VisitorPackage[7];

  attendee[0] = new VisitorPackage("Mickey", 'S', "weekday", 
"Disneyland", 75.0);
  attendee[1] = new VisitorPackage("Donald", 'C', "weekday", 
"Disneyland", 75.0);
  attendee[2] = new VisitorPackage("Minnie", 'E', "weekend", 
"Disneyland", 75.0);
  attendee[3] = new VisitorPackage("Goofie", 'E', "weekend", 
"Disneyland", 75.0);
  attendee[4] = new VisitorPackage("Harry", 'C', "weekend", "Universal 
Studios", 60.0);
  attendee[5] = new VisitorPackage("Hermoine", 'S', "weekend", 
"Universal Studios", 60.0);
  attendee[6] = new VisitorPackage("Ron", 'E', "weekday", "Universal 
Studios", 60.0);

  //This is where I am looking for help    
  //if attendee == disneyland
  for(int i=0; i < attendee.length; i++)
  {
    {
      attendee[i].applyDiscount(attendee[i], 5.0, 10.0);
      attendee[i].applyWeekdayRate(attendee[i], 15.0);
      attendee[i].printInfo(attendee[i]);
      totalAttendeeCost += attendee[i].getTotalCost();
    }
  }

  //else if attendee == universal
  for(int i=0; i < attendee.length; i++)
  {
      attendee[i].applyDiscount(attendee[i], 10.0, 15.0);
      attendee[i].applyWeekdayRate(attendee[i], 20.0);
      attendee[i].printInfo(attendee[i]);
      totalAttendeeCost += attendee[i].getTotalCost();
  }

  //System.out.println("Total: $" + totalCostDisney + "\n");
  System.out.println("--------------");
  System.out.printf("Total: $%.2f\n", totalAttendeeCost);

  }
} 

Here is the other class containing the methods:

public class VisitorPackage
{  
private String visitorName;
private char visitorType;
private String visitDay;
private String destination;
private double totalCost;

public VisitorPackage()
{
   visitorName ="N/A";
   visitorType = '-';
   visitDay = "-";
   destination = "N/A";
   totalCost = 0.0;
}

public VisitorPackage(String newVisitorName, char newVisitorType, 
String newVisitDay, String newDestination, double newTotalCost)
{
   visitorName = newVisitorName;
   visitorType = newVisitorType;
   visitDay = newVisitDay;
   totalCost = newTotalCost;
   destination = newDestination;
}   

public String getDestinationPark(VisitorPackage arrayInstance)
{
   if (arrayInstance.destination.equalsIgnoreCase("disneyland"))
    return destination;
   else
    return destination;
}

public double getTotalCost()
{
   return totalCost;
}

public void applyDiscount(VisitorPackage arrayInstance, double 
childRate, double seniorRate)
{
   if (arrayInstance.visitorType == 'C')
       totalCost -= ((totalCost * childRate) / 100);
   else if (arrayInstance.visitorType == 'S')
           totalCost -= ((totalCost * seniorRate) / 100);
}

 public void applyWeekdayRate(VisitorPackage arrayInstance, double 
 weekdayDiscount)
{
   if (arrayInstance.visitDay.equalsIgnoreCase("weekday"))
      totalCost -= weekdayDiscount;
}

public void printInfo(VisitorPackage arrayInstance)
{
   System.out.print(arrayInstance.visitorName + " - ");
   System.out.print(arrayInstance.destination + " - ");
   System.out.print("$");
   System.out.printf("%.2f", arrayInstance.totalCost);
   if (arrayInstance.visitorType == 'E')
      System.out.print("   ***** Discount cannot be applied to " + 
 arrayInstance.visitorName);
   System.out.println();
  }
 }

Upvotes: 1

Views: 103

Answers (2)

Tom Drake
Tom Drake

Reputation: 537

In addition to the code issues pointed out by DevilsHnd, I wanted to steer you in a different direction.

  • Using streams to get the reporting you were looking for, and
  • Instead of using strings to represent things like Destination, Visitor Type and Visit Day, using enums to represent these concepts can clean up your code quite a bit and make it very clear how the discounting scheme works.

I've refactored your code accordingly

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.summingDouble;

public class Visitor {

    public enum VisitorType {
        Child, Senior, Other
    }
    public enum VisitType {
        Weekday,Weekend
    }
    // represents each Destination as well as all related discount rates.
    public enum Destination { 
    Disneyland {
        {
            visitorDiscount.put(VisitorType.Child, 5.0);
            visitorDiscount.put(VisitorType.Senior, 10.0);
            visitTypeDiscount.put(VisitType.Weekday, 15.0);
        }
      }
      , UniversalStudios {
        {
            visitorDiscount.put(VisitorType.Child, 10.0);
            visitorDiscount.put(VisitorType.Senior, 15.0);
            visitTypeDiscount.put(VisitType.Weekday, 20.0);
        }
      };

    protected Map<VisitorType,Double> visitorDiscount= new HashMap();
    protected Map<VisitType,Double> visitTypeDiscount= new HashMap();
    public double getVisitorTypeDiscount(VisitorType visitorType) {
        Double discount = visitorDiscount.get(visitorType);
        return discount == null ? 0.0 : discount;
    }
    public double getVisitTypeDiscount(VisitType visitType) {
        Double discount = visitTypeDiscount.get(visitType);
        return discount == null ? 0.0 : discount;
    }
  }; 
  public static class VisitorPackage {

    private final String visitorName;
    private final VisitorType visitorType;
    private final VisitType visitDay;
    private final Destination destination;
    private final double totalCost;

    public VisitorPackage(String newVisitorName, VisitorType newVisitorType,
            VisitType newVisitDay, Destination newDestination, double newTotalCost) {
        visitorName = newVisitorName;
        visitorType = newVisitorType;
        visitDay = newVisitDay;
        totalCost = newTotalCost;
        destination = newDestination;
    }

    public String getDestinationPark() {
        return destination.toString();
    }

    public double getTotalCost() {
        return totalCost;
    }
    public double getDiscountedCost() {
        double visitorTypeDiscount = totalCost * destination.getVisitorTypeDiscount(visitorType)/100;
        return totalCost - visitorTypeDiscount - destination.getVisitTypeDiscount(visitDay);
    }
    public Destination getDestination() { return destination; }

    public void printInfo() {
        System.out.print(visitorName + " - ");
        System.out.print(destination + " - ");
        System.out.printf("$%.2f -> ", getTotalCost());
        System.out.print("$");
        System.out.printf("%.2f", getDiscountedCost());
        if (visitorType == VisitorType.Other) {
            System.out.print("   ***** Discount cannot be applied to "
                    + visitorName);
        }
        System.out.println();
      }

    }
    public static void main(String args[]) {

        double totalAttendeeCost = 0.0;

        //Using 1 array
        VisitorPackage[] attendee = new VisitorPackage[7];

        attendee[0] = new VisitorPackage("Mickey", VisitorType.Senior, VisitType.Weekday,
            Destination.Disneyland, 75.0);
        attendee[1] = new VisitorPackage("Donald", VisitorType.Child, VisitType.Weekday,
            Destination.Disneyland, 75.0);
        attendee[2] = new VisitorPackage("Minnie", VisitorType.Other, VisitType.Weekend,
            Destination.Disneyland, 75.0);
        attendee[3] = new VisitorPackage("Goofie", VisitorType.Other, VisitType.Weekend,
            Destination.Disneyland, 75.0);
        attendee[4] = new VisitorPackage("Harry", VisitorType.Child, VisitType.Weekend, Destination.UniversalStudios, 60.0);
        attendee[5] = new VisitorPackage("Hermoine", VisitorType.Senior, VisitType.Weekend,
            Destination.UniversalStudios, 60.0);
        attendee[6] = new VisitorPackage("Ron", VisitorType.Other, VisitType.Weekday, Destination.UniversalStudios, 60.0);

        // Print a report grouped by Destination showing all VisitoerPackages and their discounted costs with subtotals
        Arrays.stream(attendee)
            .collect(groupingBy(VisitorPackage::getDestination))
            .entrySet().stream()
            .forEach(e->{
                System.out.println("Summary for "+e.getKey());
                e.getValue().stream().forEach(VisitorPackage::printInfo);
                Double total = e.getValue().stream().collect(summingDouble(VisitorPackage::getDiscountedCost));
                System.out.printf("Total Discounted Cost for %s = $%.2f\n",e.getKey(),total);
                System.out.println("------------------------------------------------------------");
            });

        // Here's a way to reduce the dataset to map of sub-totals keyed by destination.
        Map<Destination,Double> discountedCostByDest = Arrays.stream(attendee)
            .collect(groupingBy(
                    VisitorPackage::getDestination, 
                    summingDouble(VisitorPackage::getDiscountedCost)));
        System.out.println(discountedCostByDest);

        // compute and display the total cost.
        Double totalDiscountedCost = Arrays.stream(attendee)
            .collect(summingDouble(VisitorPackage::getDiscountedCost));
        System.out.printf("Grand Total = $%.2f\n", totalDiscountedCost);
    }
}

This code produces the following output:

Summary for UniversalStudios
Harry - UniversalStudios - $60.00 -> $54.00
Hermoine - UniversalStudios - $60.00 -> $51.00
Ron - UniversalStudios - $60.00 -> $40.00   ***** Discount cannot be     applied to Ron
Total Discounted Cost for UniversalStudios = $145.00
------------------------------------------------------------
Summary for Disneyland
Mickey - Disneyland - $75.00 -> $52.50
Donald - Disneyland - $75.00 -> $56.25
Minnie - Disneyland - $75.00 -> $75.00   ***** Discount cannot be applied to Minnie
Goofie - Disneyland - $75.00 -> $75.00   ***** Discount cannot be applied to Goofie
Total Discounted Cost for Disneyland = $258.75
------------------------------------------------------------
{UniversalStudios=145.0, Disneyland=258.75}
Grand Total = $403.75

Upvotes: 1

DevilsHnd - 退した
DevilsHnd - 退した

Reputation: 9192

Keep in mind, each element of your attendee array is a specific instance of VisitorPackage. So, utilize your Getter methods within the VisitorPackage Class, but first get rid of the parameter for that method and simplify it like this:

public String getDestinationPark() {
    return this.destination;
}

Do the same for all your other methods within the VisitorPackage Class, get rid of the VisitorPackage arrayInstance parameter and any relation to it within your class methods, like this:

public void applyDiscount(double childRate, double seniorRate) {
    if (visitorType == 'C') {
        totalCost -= ((totalCost * childRate) / 100);
    }
    else if (visitorType == 'S')
       totalCost -= ((totalCost * seniorRate) / 100);
}

public void applyWeekdayRate(double weekdayDiscount) {
   if (visitDay.equalsIgnoreCase("weekday")) {
       totalCost -= weekdayDiscount;
   }
}

public void printInfo() {
    System.out.print(visitorName + " - ");
    System.out.print(destination + " - ");
    System.out.print("$");
    System.out.printf("%.2f", totalCost);

    if (visitorType == 'E') {
        System.out.print("   ***** Discount cannot be applied to " + visitorName);
    } 
    System.out.println();
}

Because each element of the attendee array is an instance of the VisitorPackage Class you don't need to send that instance to your class methods. It already knows which instance you are referring to (Mickey, Donald, Ron, etc) when you supply the Index number. Since Minnie is at index 2 of the attendee array any calls to the VisitorPackage class like attendee[2].applyWeekdayRate(15.0) will only ever apply to Minnie.

Now, when you want to process the attendee's Array:

// iterate through each attendee and 
// apply necessary discounts, etc.
for (int i = 0; i < attendee.length; i++) { 
    // Disneyland
    if (attendee[i].getDestinationPark().equalsIgnoreCase("disneyland")) {
        attendee[i].applyDiscount(5.0, 10.0);
        attendee[i].applyWeekdayRate(15.0);
        attendee[i].printInfo();
        totalAttendeeCost += attendee[i].getTotalCost();
    }
    // Universal Studios
    else if (attendee[i].getDestinationPark().equalsIgnoreCase("universal studios")) {
        attendee[i].applyDiscount(10.0, 15.0);
        attendee[i].applyWeekdayRate(20.0);
        attendee[i].printInfo();
        totalAttendeeCost += attendee[i].getTotalCost();
    }
}

Or you could do it like this:

for (int i = 0; i < attendee.length; i++) { 
    String dest = attendee[i].getDestinationPark();
    if (dest.equalsIgnoreCase("disneyland")) {
        attendee[i].applyDiscount(5.0, 10.0);
        attendee[i].applyWeekdayRate(15.0);
        attendee[i].printInfo();
        totalAttendeeCost += attendee[i].getTotalCost();
    }
    else if (dest.equalsIgnoreCase("universal studios")) {
        attendee[i].applyDiscount(10.0, 15.0);
        attendee[i].applyWeekdayRate(20.0);
        attendee[i].printInfo();
        totalAttendeeCost += attendee[i].getTotalCost();
    }
}

Or you could do it like this:

for (int i = 0; i < attendee.length; i++) { 
    String dest = attendee[i].getDestinationPark();
    switch (dest.toLowerCase()) {
        case "disneyland":
            attendee[i].applyDiscount(5.0, 10.0);
            attendee[i].applyWeekdayRate(15.0);
            attendee[i].printInfo();
            totalAttendeeCost += attendee[i].getTotalCost();
            break;
        case "universal studios":   // if the string has a space
        case "universalstudios":    // OR if the string has no space
            attendee[i].applyDiscount(10.0, 15.0);
            attendee[i].applyWeekdayRate(20.0);
            attendee[i].printInfo();
            totalAttendeeCost += attendee[i].getTotalCost();
            break;
    }
}

Upvotes: 1

Related Questions