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

#java #for-loop #arraylist

#java #for-цикл #arraylist

Вопрос:

Я должен создать метод, который возвращает все моноблоки, вес которых больше или равен входному параметру, в данном случае больше 1,75. Я попытался создать свой собственный метод, но, похоже, он не работает.. Любые предложения или помощь будут оценены. Я собираюсь опубликовать оба метода внизу.. Я пытался использовать forloop, но я не знаю, как сложить числа вместе.

Главная:

  import java.util.ArrayList;

    public class Lab16
 {
   public static void main(String[] args)
  {
    ArrayList<CandyBar> bars = new ArrayList<CandyBar>();
    addCandyBarsToList(bars);

    /**
     * Use the methods you wrote below to answer all of
     * the following questions.
     */

    /**
     * Part A:
     */

    /**
     * Is Twix in the list?
     * If so, print all information about it.
     * If not, print a message to the user.
     */

    int location = findCandyBar(bars, "Twix");
    if(location == -1){
        System.out.println("The Candy bar is not in the list");
    } else{
        bars.get(location).printInfo();
    }

    /**
     * Is Mounds in the list?
     * If so, print all information about it.
     * If not, print a message to the user.
     */
    System.out.println();
    int index = findCandyBar(bars, "Mounds");
    if(index == 1){
        System.out.println("The Candy bar is not in the list");
    } else{
        bars.get(index).printInfo();
    }
    /**
     * Part B:
     */

    /**
     * Print all the names of candy bars with yellow wrappers.
     */

    findByColor(bars, CandyBar.Color.YELLOW);


    /**
     * Part C:
     */

    /**
     * Count how many candy bars are 1.75 oz or more.
     */
    double weight = countByWeight(bars, 1.75);
    if(weight >= 1.75){
        System.out.println(weight);
    }else{
        System.out.println("They are no candy bars with that much weight");
    }



    /**
     * Part D:
     */

    /**
     * Is there a candy bar that is 1.86 oz?
     * If so, print the information.
     * If not, print a message to the user.
     * Write a binary search method to get the answer.
     */


}

/**
 * This method searches a list to find a candy bar by name.
 *
 * @param   list    the list to search
 * @param   n       a name to find
 * @return          the index of the candy bar 
 */
public static int findCandyBar(ArrayList<CandyBar> list, String n)
{ 
    for(int i = 0; i < list.size(); i  ){
        if(list.get(i).getName() == n){
            return i;
        }
}
return 1;
}
/**
 * This method prints the names of the candy bars that have a certain
 * wrapper color.
 *
 * @param   list    the list to search
 * @param   c       the color wrapper to find 
 */
public static void findByColor(ArrayList<CandyBar> list, CandyBar.Color c)
{
    for(int i = 0; i < list.size(); i  ){
        if(list.get(i).getWrapperColor() == CandyBar.Color.YELLOW){
       System.out.println(list.get(i));
    }  else{
      System.out.println("There is no such candy bar with that color");
}
}
 

}

 /**
 * This method counts the number of candy bars that weigh greater than
 * or equal to the weight input parameter.
 *
 * @param   list    the list to search
 * @param   w       the weight to compare to
 * @return          the count of candy bars 
 */
public static int countByWeight(ArrayList<CandyBar> list, double weight)
{
    for(int i = 0; i < list.size(); i  ){
        if(list.get(i).getWeight() >= 1.70){
            return 
     }
 }
 return 1;
}
/**
 * This method searches a list using binary search.
 *
 * @param   list    the list to search
 * @param   first   the first index
 * @param   last    the last index
 * @param   w       the value to search for
 * @return          the index of the candy bar 
 */
public static int binaryFind(ArrayList<CandyBar> list, int first, int last, double w)
{
    return -1;
}

/**
 * This method adds candy bars to a list.
 *
 * @param   list    the list to add to
 */
public static void addCandyBarsToList(ArrayList<CandyBar> list)
{
    CandyBar kitkat = new CandyBar("KitKat", CandyBar.Color.RED, 1.5);
    list.add(kitkat);
    CandyBar grand = new CandyBar("One-hundred Grand", CandyBar.Color.RED, 1.5);
    list.add(grand);
    CandyBar crunch = new CandyBar("Crunch", CandyBar.Color.BLUE, 1.55);
    list.add(crunch);
    CandyBar hershey = new CandyBar("Hershey", CandyBar.Color.BROWN, 1.55);
    list.add(hershey);
    CandyBar krackel = new CandyBar("Krackel", CandyBar.Color.RED, 1.55);
    list.add(krackel);
    CandyBar caramello = new CandyBar("Caramello", CandyBar.Color.PURPLE, 1.6);
    list.add(caramello);
    CandyBar what = new CandyBar("Whatchamacallit", CandyBar.Color.YELLOW, 1.6);
    list.add(what);
    CandyBar almond = new CandyBar("Almond Joy", CandyBar.Color.BLUE, 1.61);
    list.add(almond);
    CandyBar goodbar = new CandyBar("Mr. Goodbar", CandyBar.Color.YELLOW, 1.75);
    list.add(goodbar);
    CandyBar twix = new CandyBar("Twix", CandyBar.Color.GOLD, 1.79);
    list.add(twix);
    CandyBar henry = new CandyBar("Oh Henry", CandyBar.Color.YELLOW, 1.8);
    list.add(henry);
    CandyBar milkyWay = new CandyBar("Milky Way", CandyBar.Color.GREEN, 1.84);
    list.add(milkyWay);
    CandyBar payDay = new CandyBar("PayDay", CandyBar.Color.ORANGE, 1.85);
    list.add(payDay);
    CandyBar snickers = new CandyBar("Snickers", CandyBar.Color.BLUE, 1.86);
    list.add(snickers);
    CandyBar butterfinger = new CandyBar("Butterfinger", CandyBar.Color.YELLOW, 1.9);
    list.add(butterfinger);
    CandyBar musketeers = new CandyBar("Three Musketeers", CandyBar.Color.SILVER, 1.92);
    list.add(musketeers);
    CandyBar reeses = new CandyBar("Reese's FastBreak", CandyBar.Color.ORANGE, 2);
    list.add(reeses);
    CandyBar babyRuth = new CandyBar("Baby Ruth", CandyBar.Color.SILVER, 2.1);
    list.add(babyRuth);
}
 

}

Метод:

 public class CandyBar
     {
       public enum Color { BLUE, BROWN, GOLD, GREEN, ORANGE, PURPLE, RED, SILVER, WHITE, YELLOW }

// instance variables
private String name;
private double weight;
private Color wrapper;

/**
 * Constructor for objects of class CandyBar
 */
public CandyBar(String n, Color c, double w)
{
    this.name = n;
    this.weight = w;
    this.wrapper = c;
}

public String getName()
{
    return this.name;
}

public double getWeight()
{
    return this.weight;
}

public Color getWrapperColor()
{
    return this.wrapper;
}

public void printInfo()
{
    System.out.println(this.name);
    System.out.printf("%.1f oz with a ", this.weight);
    System.out.println(this.wrapper   " wrapper");
}
 

}

Комментарии:

1. Проблема здесь: if(list.get(i).getName() == n){

2. Не сравнивайте строки с помощью == или != . equals(...) Вместо этого используйте метод equalsIgnoreCase(...) или. Поймите, что == проверяет, совпадают ли две ссылки на объекты , что вас не интересует. С другой стороны, методы проверяют, имеют ли две строки одинаковые символы в одном и том же порядке, и это то, что здесь важно.

3. Кроме того, ваш countByWeight(...) не подсчитывает, но немедленно возвращается, если найден какой-либо моноблок, который соответствует или превышает желаемый вес. Имеет ли это логический смысл для вас? Таким образом, у вас проблема с базовой логикой, а не с синтаксисом кодирования.

4. Я все еще новичок в этом, но я понимаю, что вы имеете в виду. Ну, как мне заставить метод возвращать количество моноблоков больше 1,75?

5. Вам нужна переменная счетчика для увеличения каждый раз, когда вы видите полосу с большим весом. Затем, как только вы закончите цикл, верните переменную counter .

Ответ №1:

Вот как посчитать бары, которые тяжелее или равны указанному весу:

 public static int countByWeight(ArrayList<CandyBar> list, double weight)
{
    int countOfBarsHeavierOrEqual = 0;
    for(int i = 0; i < list.size(); i  ){
        if(list.get(i).getWeight() >= weight){
            countOfBarsHeavierOrEqual  ; 
        }
    }
    return countOfBarsHeavierOrEqual;
}
 

Кроме того, ваша findCandyBar() реализация должна быть:

 public static int findCandyBar(ArrayList<CandyBar> list, String n)
{ 
    for(int i = 0; i < list.size(); i  ){
        if(list.get(i).getName().equals(n)){
            return i;
        }
    }
    return -1;
}
 

Затем исправьте это выполнение:

 int index = findCandyBar(bars, "Mounds");
if(index == -1){    // <-- check for -1 to see if not found
 

РЕДАКТИРОВАТЬ: один из способов сделать очевидной ситуацию «не найдено» — установить константу в верхней части вашего класса:

 private static final int NOT_FOUND = -1;
 

Тогда везде, где вы хотите вернуть что-то, что не было найдено, или проверить его:

 return NOT_FOUND;
 

… или …

 if(index == NOT_FOUND){
 

Комментарии:

1. Теперь это имеет большой смысл. Спасибо за вашу помощь!!

Ответ №2:

Попробуйте это:

 public static int countByWeight(ArrayList<CandyBar> list, double weight) {
    return (int)list.stream().map(CandyBar::getWeight).filter(w -> w >= weight).count();
}
 

Обратите внимание, что ваш код проигнорировал weight параметр и вместо этого жестко запрограммирован 1.70 как пороговое значение.

Комментарии:

1. Правильно — если OP использует Java8 .

2. @Jason java 8??? Цитирую документ : Java SE 8 завершила процесс общедоступных обновлений

3. Более старые версии, чем Java8, все еще используются во всем мире. То, что Java8 попал в конец общедоступных обновлений, не означает, что он или его предшественники больше не работают или больше не используются.

4. Не поймите меня неправильно — я сторонник потоков. Ваше решение — это то, как я обычно это делаю. Я просто думаю, что люди, изучающие Java, должны также изучить «старый» способ ведения дел, чтобы они понимали, как все работает.