我的链表方法用于计算对象的出现次数似乎没有终止有什么想法吗?

jaxagkaj  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(379)

嘿,谢谢你花时间看我的代码!我非常感谢你。为了给大家一点背景知识,我之前为一个任务创建了一个口袋妖怪排序数组。现在,下一个任务是做所有相同的事情,除了使用链表(不导入自动工具,我们从头开始)。就我所知,这只需要在循环时为链表切换基于数组的for循环。问题出在这里。我的计数方法已经破坏了我的代码几个小时了,现在我知道该怎么做了。该方法应该将一个布尔示例作为参数,并将其与我列表中的口袋妖怪进行比较(我的布尔示例变量是watertype,然后返回与之匹配的口袋妖怪数量)。我试着用3参数构造函数在方法内部构造一个新的口袋妖怪,只填充布尔示例,同时保留字符串和int“null”和“0”,但这会在线程“main”java.lang.nullpointerexception:无法调用“string.tolowercase()”,因为orderedlistapp/orderedlistapp.pokemon.compareto(pokemon.java:58)和orderedlistapp/orderedlistapp.pokemonlinkedlist.CountOccents(pokemonlinkedlist.java:64)处的“temp.name”为nullorderedlistapp/orderedlistapp.driver.main(driver.java:22)“然后我尝试在方法中创建一个新的口袋妖怪,该方法与我列表中的口袋妖怪完全匹配所有三个变量,现在程序甚至不会终止。如果我在运行时将该方法放在其他方法之前,其他方法甚至不会输出。如果这里有人有什么想法,我一定会很感激的!另外,请原谅我所有被注解掉的部分,这些是我尚未更新为链表格式(或尝试更新)的方法。

package orderedListApp;

public class Pokemon {
    private String name;
    private int hp;
    private boolean waterType;
    public Pokemon(String name, int hp, boolean waterType) {
        this.name= name;
        this.hp = hp;
        this.waterType = waterType;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getHp() {
        return hp;
    }

    public void setHp(int hp) {
        this.hp = hp;
    }

    public boolean isWaterType() {
        return waterType;
    }

    public void setWaterType(boolean waterType) {
        this.waterType = waterType;
    }

    public int compareTo(String anotherString) {
        return name.compareTo(anotherString);
    }
      @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final Pokemon other = (Pokemon) obj;
            if (!this.name.equalsIgnoreCase(other.name)) {
                return false;
            }
            return true;
        }
      public int compareTo(Pokemon temp) {
            return this.name.toLowerCase().compareTo(temp.name.toLowerCase());
        }
    @Override
    public String toString() {
        String output = "";
        output += name + "\t\t" + hp + "\t\t" + waterType;
        return output;
    }

}

package orderedListApp;

public class PokemonNode {
    private PokemonNode link;
    private Pokemon data;

    public PokemonNode(Pokemon data, PokemonNode link) {
        this.link = link;
        this.data = data;
    }

    public PokemonNode getLink() {
        return link;
    }

    public void setLink(PokemonNode link) {
        this.link = link;
    }

    public Pokemon getData() {
        return data;
    }

    public void setData(Pokemon data) {
        this.data = data;
    }

}

package orderedListApp;

import java.util.Iterator;

public class PokemonLinkedList implements Iterable<Pokemon> {

    PokemonNode head;
    // variable to store size
    int manyItems;

    // constructor
    public PokemonLinkedList() {
        head = null;
        manyItems = 0;
    }

    public void insert(Pokemon poke) {
        if (head == null) {
            head = new PokemonNode(poke, null);
        } else if (poke.compareTo(head.getData()) < 0) {
            head = new PokemonNode(poke, head);
        } else {
            PokemonNode previous = findPreviousNode(poke);
            previous.setLink(new PokemonNode(poke, previous.getLink()));
        }
        manyItems++;
    }

    private PokemonNode findPreviousNode(Pokemon poke) {
        PokemonNode cursor = head;
        while (cursor.getLink() != null && cursor.getData().compareTo(poke) < 0)
            ;
        {

            cursor = cursor.getLink();
        }
        return null;
    }

    // method to return total number of pokemon in the list
    public int size() {
        return this.manyItems;
    }

    public void removePokemon(Pokemon poketoRemove) {
        if (head != null && head.getData().equals(poketoRemove)) {
            head = head.getLink();
        } else if (head != null) {
            PokemonNode previous = findPreviousNodeRemove(poketoRemove);
            previous.setLink(previous.getLink().getLink());
        }
    }

    private PokemonNode findPreviousNodeRemove(Pokemon pokeToRemove) {
        PokemonNode cursor = head;
        while (cursor.getLink() != null && !cursor.getData().equals(pokeToRemove)) {
            cursor = cursor.getLink();

        }
        return cursor;
    }

    public int countOccurrences(boolean b) {
        PokemonNode cursor = head;
        int count = 0;
        Pokemon poke = new Pokemon(null, 0, true);
        while (cursor != null) {
            if (cursor.getData().compareTo(poke) == 0)
                cursor = cursor.getLink();
            count++;
        }
        return count;
    }

//      public boolean contains(Pokemon oneThing) {
//          for(int i=0; i<size; i++){
//              if(pokemon[i].equals(oneThing))
//                  return true;
//          }
//          return false;
//      }

//      public int total() {
//          int total = 0;
//          for(int i=0; i<size; i++){
//              total += pokemon[i].getHp();
//          }
//          return total;
//      }
//      public int countRange(int low, int high) {
//          if(low>high)
//              return 0;
//          int count = 0;
//          PokemonNode cursor = head;
//          while(cursor != head) {
//              if(cursor )
//          }
//          
//          return count;
//          

//       for(int i=0; i<size; i++){
//              if(pokemon[i].getHp()>=low && pokemon[i].getHp()<=high)
//                  count++;
//          }
//          return count;
    // }
    // toString method
    @Override
    public String toString() {
        String output = "Type" + "\t\t" + "Hp" + "\t\t" + "Water type" + "\n";
        output += "------------------------\n";

        PokemonNode cursor = head;
        while (cursor != null) {
            output += cursor.getData() + "\n";
            cursor = cursor.getLink();
        }
        return output;
    }

    private class PokemonIteratorClass implements Iterator<Pokemon> {
        int cursor = 0;

        @Override
        public boolean hasNext() {

            return cursor < manyItems;
        }

        @Override
        public Pokemon next() {

            return head.getData();
        }

    }

    @Override
    public Iterator<Pokemon> iterator() {
        // TODO Auto-generated method stub
        return null;
    }

//      public Iterator<Pokemon> iterator() {
//          Iterator<Pokemon> it = new Iterator<Pokemon>() {
//              private int currentIndex = manyItems-1;
//              @Override
//              System.out.println("LinkedList elements:");
//              while(it.hasNext()){
//                 System.out.println(it.next());
//          };
//          return it;

//  }
//  }
}

package orderedListApp;

public class Driver {

    public static void main(String[] args) {

        // PokemonOrderedList pokemon = new PokemonOrderedList(10);
        PokemonLinkedList pokemon2 = new PokemonLinkedList();
        pokemon2.insert(new Pokemon("Pikachu", 2, false));
        pokemon2.insert(new Pokemon("Gigachu", 2, true));
        // pokemon.insert(new Pokemon("Pikachu ", 2, false));
        // pokemon.insert(new Pokemon("Squirtle", 3, true));
        // pokemon.insert(new Pokemon("Geodude ", 2, false));
        // pokemon.insert(new Pokemon("Meowth ", 2, false));
        // pokemon.insert(new Pokemon("Magicarp", 1, true));

        System.out.println("Collection size: " + pokemon2.size());
        System.out.println(pokemon2);
        System.out.println("Water types: " + pokemon2.countOccurrences(true));
//              System.out.println("Find Pokemon: "+pokemon.find("Magicarp"));
//              System.out.println("Contains Geodude?: "+pokemon.contains(new Pokemon("Geodude  ", 2, false)));
//              System.out.println("Contains Onyx?: "+pokemon.contains(new Pokemon("Gremlin", 2, false)));
//              System.out.println("Total hp: "+pokemon.total());
//              System.out.println("Average hp is: " + pokemon.average());
//              System.out.println("Number of pokemon with hp between the entered range: " + pokemon.countRange(1, 30));

    }

}
46scxncf

46scxncf1#

你现在 CountOccurences() 代码相当混乱。它似乎总是增加计数,而不考虑 waterType 变量,并且仅当满足奇数条件时才在列表中继续。请尝试以下方法:

public int countOccurrences(boolean b) {
    PokemonNode cursor = head;
    int count = 0;
    while (cursor != null) {
        if (cursor.getData().isWaterType() == b) 
            count++;
        cursor = cursor.getLink();
    }
    return count;
}

这将检查 waterType 每个口袋妖怪的值等于查询布尔值 b ,如果是,则在计数中添加一个。

相关问题