Как настроить if-else в Java для разбора элементов массива - PullRequest
0 голосов
/ 06 декабря 2018

Я пытаюсь настроить свой Java-код для анализа того, посещал ли элемент моего массива студии Disneyland или Universal.В моем массиве 7 элементов для 7 участников.Участники получают скидки в зависимости от того, в каком парке они побывали, и я создал два цикла for для представления двух парков.

Как настроить код в основном методе, чтобы определить, куда и куда ходили участники?

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 голосов
/ 06 декабря 2018

В дополнение к проблемам с кодом, указанным 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
0 голосов
/ 06 декабря 2018

Имейте в виду, что каждый элемент вашего участника является конкретным экземпляром VisitorPackage .Итак, используйте ваши Getter методы в VisitorPackage Class, , но сначала избавьтесь от параметра для этого метода и упростите его следующим образом:

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

Поскольку каждый элемент массива посетители является экземпляром класса VisitorPackage, вам не нужно отправлять этот экземпляр в методы класса.Он уже знает, на какой экземпляр вы ссылаетесь (Микки, Дональд, Рон и т. Д.), Когда вы указываете номер индекса.Поскольку Минни находится в индексе 2 массива участника , любые вызовы класса 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;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...