尝试在实例类中输出链接列表的内容时,无法从静态上下文错误引用方法

时间:2015-04-07 01:33:04

标签: java static linked-list

我是初学者Java程序员,我试图检查我是否已成功将存储在类客户端中的链表中的Person实例复制到名为passenger的实例中的链接列表中。通过船打印出船的链接列表的内容。

我正在使用Boat类的方法givePassengers()将Boat类打印输出给乘客链接列表内容。

然而,当我尝试这样做时,我遇到错误'非静态方法givePassengers()无法从静态上下文中引用'而且我不确定写什么来解决这个问题。我列出了我认为是下面的问题代码。非常感谢任何帮助。

我已经用' // !!'

标记了重要代码

这是包含船只链接列表的类

import java.io.*;
import java.util.*;

public class Base implements Serializable
{   private LinkedList<Boat> boats = new LinkedList<Boat>();
    private Clients clients = new Clients();

public void setup() // !! Here are the instances of the boat class
    {   boats.add(new Boat(1, "Ed", 2));
        boats.add(new Boat(2, "Fred", 7));
        boats.add(new Boat(3, "Freda", 5));   }


  public void showpassengers() {

        for (Boat i: boats) `// !! The for each loop cycles through each boat to check for passengers`
           Boat.givePassengers(); // !! This line produces the error
    }

这是船类

import java.io.*;
import java.util.*;

public class Boat implements Serializable
{   private int id;
    private String pilot;
    private int stops;
    private LinkedList<Person> passengers = new LinkedList<Person>();
    private double rate = 10.00;
    public int scannableId = this.id;

 public Boat(int id, String pilot, int stops)
    {   this.id = id;
        this.pilot = pilot;
        this.stops = stops;   }



    public void givePassengers () {

System.out.println(passengers); // !! this line is supposed to print out the contents of the boat classes' linked list so I can check that it worked.

        }

这是Person类

import java.io.*;
import java.text.*;

public class Person implements Serializable
{   private String name;
    private int id;
    private double cash = 100.00;
    private int start = 0;
    private int end = 0;
    private double charge = 0;

   public Person(String name, int id)
    {   this.name = name;
        this.id = id + 100; }
}

这是包含Person

链接列表的类
import java.io.*;
import java.util.*;

public class Clients implements Serializable
{   private LinkedList<Person> clients = new LinkedList<Person>();
    private int id = 1;

    public Clients() `// !! Here are the instances of Person in the class clients`
    {   clients.add(new Person("Homer", id++));
        clients.add(new Person("Marge", id++));  

    }
)

如果有帮助的话,这是根类

import java.io.*;

public class Root
{   public Root() {

        new Base();

    }

    public static void main(String[] args)
    {   new Root(); }


    private Base base;
}

2 个答案:

答案 0 :(得分:2)

你的问题在这里:

for (Boat i: boats) 
   Boat.givePassengers(); // !! This line produces the error

您需要说i.givePassengers()来引用类Boat的特定实例。关于类和对象之间差异的良好入门here

答案 1 :(得分:1)

你不能从Boat静态调用givePassengers(),它不是静态方法。你需要从Boat的一个实例中调用它。在foreach循环中将Boat.givePassengers();替换为i.givePassengers();。这将导致当前选定的Boat实例运行givePassengers()。