首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Java中设置if-else来解析数组元素

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

Stack Overflow用户
提问于 2018-12-06 07:16:33
回答 2查看 91关注 0票数 1

我正在尝试设置我的Java代码,以解析我的数组中的某个元素是否属于迪斯尼乐园或环球影城。我的数组有7个元素,代表7个与会者。参与者可以根据他们参加的公园获得折扣,我已经创建了两个for循环来表示这两个公园。

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

代码语言:javascript
复制
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);

  }
} 

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

代码语言:javascript
复制
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();
  }
 }
EN

回答 2

Stack Overflow用户

发布于 2018-12-06 09:45:41

请记住,attendee数组的每个元素都是VisitorPackage.的一个特定实例因此,在VisitorPackage类中使用您的Getter方法,,但首先去掉该方法的参数,并像这样简化它:

代码语言:javascript
复制
public String getDestinationPark() {
    return this.destination;
}

对VisitorPackage类中的所有其他方法执行相同的操作,去掉VisitorPackage arrayInstance参数以及类方法中与它的任何关系,如下所示:

代码语言:javascript
复制
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类的一个实例,所以不需要将该实例发送到类方法。当您提供索引号时,它已经知道您引用的是哪个实例(Mickey、Donald、Ron等)。由于 Minnie 位于索引2 of attendee数组中,因此对VisitorPackage类(如attendee[2].applyWeekdayRate(15.0) )的任何调用都将仅应用于Minnie。

现在,当您想要处理attendee的数组时:

代码语言:javascript
复制
// 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();
    }
}

或者你可以这样做:

代码语言:javascript
复制
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();
    }
}

或者你可以这样做:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2018-12-06 18:45:54

除了DevilsHnd指出的代码问题之外,我还想将您引向一个不同的方向。

  • 使用streams来获取您要查找的报告,
  • 使用枚举来表示这些概念,而不是使用字符串来表示目的地、访问者类型和访问日期等内容,这将大大简化您的代码,并使折扣方案的工作方式变得非常清晰。

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

代码语言:javascript
复制
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);
    }
}

此代码生成以下输出:

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53642262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档