从文本文件打印链接列表:输出仅打印出一个名称 - Java

时间:2016-05-02 03:58:20

标签: java list printing

我有以下用Java编写的方法。我打算读出扫描器输入文本文件的名称,但此时,它只需从文件中取一个名称并显示它。

public class AssassinManager { 

private static class AssassinNode {
    private static String player; 
    private static String killer; 
    private AssassinNode next;
    private AssassinNode(String name){
        AssassinNode.player = name; 
        AssassinNode.killer = null; 
        this.next = null;
    } 
}// End of AssassinNode

private AssassinNode killring;  // the head of the kill ring linked list - first link
private AssassinNode graveyard; // the head of the graveyard linked list - second link 

/* AssasssinManager Constructor */
public AssassinManager(ArrayList<String> players){ 
    if (players == null || players.isEmpty()){ throw new IllegalArgumentException("Error: ArryList is null/empty!"); }
    AssassinNode node = killring = new AssassinNode(players.get(0)); // create first node - for the killring
    for (int i = 1; i < players.size(); i++){ // Add a new node at the end of each killing 
        node.next = new AssassinNode(players.get(i));
        node = node.next;
    }
    System.out.println(players.size());
} // End of AssassinNode Constructor - Done 

/* Prints the names of the people in the kill ring */
public void printKillRing() {
    if(killring == null){ 
        return; // break out of printKillRing method when list is null
    }
    AssassinNode node = killring; 
    do {
        if (node.next == null) {
            System.out.println(node.player + " is stlaking " + node.player);
        } else 
            System.out.println(node.player + "-->");
        node = node.next;
    } while (node != null);
} // End of printKillRing

输出: 凯莉 - &gt;凯莉 - &gt;凯莉跟踪凯莉

预期输出 凯莉 - &gt;雅各布 - &gt;罗恩

2 个答案:

答案 0 :(得分:0)

显然,AssassinNode既有名称的静态和实例字段&#34;播放器&#34;?如果不是,您需要将其更改为实例(只需从字段声明中删除static关键字)。一旦你修复了以下内容(可能?),你会得到你想要的东西。

&#13;
&#13;
    public void printKillRing(){
        if(killring == null){ 
            return; // break out of printKillRing method when list is null
        }
        AssassinNode node = killring; 
        do {
            if (node.next == null){
                System.out.println(node.player);
            } else 
                System.out.print(node.player + "-->"); // print the current element 
            node = node.next;
            
        } while (node != null);
    } // End of printKillRing
&#13;
&#13;
&#13;

答案 1 :(得分:0)

将AssassinNode类修改为,

private static class AssassinNode {
   private String player; 
   private String killer; 
   private AssassinNode next;

   private AssassinNode(String name){
       AssassinNode.player = name; 
       AssassinNode.killer = null; 
       this.next = null;
  } 
}// End of 

从播放器和杀手

中删除了static关键字