如何在Java中设置if-else以解析数组元素

时间:2018-12-05 23:16:33

标签: java arrays for-loop

我正在尝试设置Java代码以分析数组中的元素是否曾在Disneyland或Universal Studios中参加过。我的阵列有7个参与者的7个元素。与会者可以享受特定于他们参加的公园的折扣,并且我创建了两个for循环来代表两个公园。

如何在main方法中设置代码以确定哪些与会者去了哪里?

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);

  }
} 

这是另一个包含方法的类:

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();
  }
 }

2 个答案:

答案 0 :(得分:1)

请记住,您的 参与者 数组中的每个元素都是 VisitorPackage 的特定实例。因此,在 VisitorPackage 类中利用您的 Getter 方法,但首先摆脱该方法的参数并像这样简化它:

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

对VisitorPackage类中的所有其他方法执行相同的操作,摆脱 VisitorPackage arrayInstance 参数以及类方法中与该参数的任何关系,例如:

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();
}

由于 attendee 数组的每个元素都是VisitorPackage类的实例,因此您无需将该实例发送到类方法。提供索引编号时,它已经知道您要指的是哪个实例(米奇,唐纳德,罗恩等)。由于 Minnie 位于与会者数组的索引 2 上,因此对{strong> VisitorPackage 类的任何调用,例如attendee[2].applyWeekdayRate(15.0)仅适用于米妮。

现在,当您要处理与会者的数组时:

// 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();
    }
}

或者您可以这样做:

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();
    }
}

或者您可以这样做:

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;
    }
}

答案 1 :(得分:1)

除了DevilsHnd指出的代码问题外,我还想引导您朝着不同的方向发展。

  • 使用流获取您正在寻找的报告,并且
  • 使用枚举来表示这些概念,而不是使用字符串来表示“目的地”,“访问者类型”和“访问日”之类的东西,可以使您的代码更加整洁,并非常清楚折扣方案的工作原理。

我已经相应地重构了您的代码

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);
    }
}

此代码产生以下输出:

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