在 java 中的另一个 class 中存储 class 的实例

Storing instance of class in another class in java

我是初学者 java 程序员,我遇到了一个问题。

我已经用“//!!”标记了代码的关键区域,我已经包含了程序的其余部分以帮助解决任何问题。

我正在尝试将 class Clients 中链表 clients 中存储的 Person 实例存储到 class Car 实例中名为 passengers 的链表中。但是,我经常遇到需要提供字符串和 int 这两个存储在 Person 对象中的值的错误。但是我想因为我已经选择了Person class,所以这会被转移?有谁知道我要去哪里错了?

总而言之,我试图将链表(在客户中)中的对象(人)的一个实例复制到另一个class(汽车)本身的相同对象的另一个链表中一个实例(有 3 个汽车对象)

非常感谢任何帮助。

这是包含乘客链表的class车

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

public class Car implements Serializable
{   private int id;
    private String pilot;
    private int stops;
    private LinkedList<Person> passengers = new LinkedList<Person>(); // !! `Here is the linked list passengers`
    private double rate = 10.00;
    public int scannableId = this.id;
    //
    public Car(int id, String pilot, int stops)
    {   this.id = id;
        this.pilot = pilot;
        this.stops = stops;   }

    public void go()
    {   System.out.println("CarManager" + id + " with " + pilot);
        for (int stop = 0; stop < stops; stop++)
        {   charge(stop);
            if (stopAt(stop))
            {   showStop(stop);
                pay(stop); }}}



    private boolean stopAt(int i)
    {   for (Person person: passengers)
            if (person.uses(i))
                return true;
        return false;   }

    private void showStop(int i)
    {   String s = "  Stop " + i + "\n";
        String on = on(i);
        if (!on.isEmpty())
            s += "    On: " + on + "\n";
        System.out.print(s);  }

    private String on(int i)
    {   String s = "";
        for (Person person: passengers)
            if (person.getsOn(i))
                s += person.handle() + " ";
        return s;  }

    public int getId() {
        return this.id;
    }

     public int printId() {
        System.out.print(this.id);
         return this.id;
    }

    public int getStops() {

        return this.stops;

    }

    public Person AddPassenger(Person newpassenger) {  

        newpassenger = passengers.add(new Person(newpassenger)); // !! This is where I try add a new passenger, however I'm getting an error stating that I need to provide a String and int, the parameters of the Person class.

    }

这是class个人

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

    public boolean uses(int stop)
    {   return getsOn(stop) || getsOff(stop); }

    public boolean getsOn(int stop)
    {   return start == stop;  }

    public int giveStops() {

    System.out.println(this.start);
    System.out.println(this.end);
    return start;
    }

    public void setStart (int start) {

    this.start = start;

    }

     public void setOff (int stop) {

    this.end = stop;

    }

    public Person getPerson () {
        Person person = this.Person;
        return person;

    }

    public boolean getsOff(int stop)
    {   return end == stop;  }

    public String handle()
    {   return name + id;   }

    public double readCash() {

        return this.cash;

    }

    public int getId() {

        return this.id;

    }

    public String getName() {

        return this.name;

    }

    @Override
    public String toString() {
        String result = "  " + this.name + " (Scuba" + this.id + ") has "  + formatted(this.cash); 
        return result;
    }

    private String formatted(double amount)
    {   DecimalFormat twoD = new DecimalFormat("$###,##0.00");
        return twoD.format(amount);  }

    public boolean matches(String name)
    { return this.name.equals(name) || name.equals(this.name + this.id); }

}

这里是 carManager class,它包含 Car 对象的链表。

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

public class CarManager implements Serializable
{   private LinkedList<Car> cars = new LinkedList<Car>();
    private Clients clients = new Clients();


    public CarManager(){
        setup();
        menu();

    }
// !! Here is where the cars are created 
    public void setup()
    {   cars.add(new Car(1, "Ed", 2));
        cars.add(new Car(2, "Fred", 7));
        cars.add(new Car(3, "Freda", 5));   }


    public void menu() {
        char choice;
        while ((choice = readChoice()) !='x' ) {
            switch(choice) {
                case 'a': clients.makePerson(); break;
                case 's': clients.showClients(); break;
                case 'r':clients.removeClient(); break;
                case 'b': findCar(); break;
                case 'c': clients.getClient(); break;

                default: showMenu();
            }

        }   
    }

    private int nextInt() {

        return In.nextInt();

    }

    public void findCar() {
        System.out.print("Car:  ");
        int searchid = In.nextInt();
        boolean carfound = false;
        for (Car i: cars)
        { 
            if (searchid == i.getId())
            {
                carfound = true;
                System.out.println("  Stops  0-" + i.getStops());

                getClientId();

                Car thecar = i; 
              } 

            if (carfound == false)
                System.out.println("  No such car");
        }
    }



    public void getClientId() {

        clients.theSiv();

    }


    private void showMenu() {
        System.out.println("The menu choices are ");
        System.out.println("  a: add a client");
        System.out.println("  r: remove a client ");
        System.out.println("  b: make a booking");
        System.out.println("  g: go (run the s)");
        System.out.println("  s: show the clients");
        System.out.println("  f: store and exit");
        System.out.println("  x: exit");
    }

    private char readChoice() {
        System.out.print("Your choice: ");
        return In.nextChar();
    }

    public void exit() {

        System.exit(0);

    }



}

这是客户端 class,它包含链接列表客户端,其中包含我要添加到 Car 实例的 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()
    {   clients.add(new Person("Homer", id++));
        clients.add(new Person("Marge", id++));  

    }

    public  void makePerson(){

        clients.add(createPerson());

    }

    public void removeClient() {

        String searchname = readName();
        boolean removed = false;

        for (Person i:clients)
            if  (i.matches(searchname)){
                clients.remove(i); 
                removed = true;
        }

        if (removed == false)
            System.out.println("  No such client");

    }

    public void theSiv() {
        System.out.println("  CarManager id: ");
        String s = In.nextLine();
        boolean isValidInteger = false;
        char choice = 'p';
        int foundid = 0;
        boolean exists = false;
        int searchid = 0;
        try
        {
            int i = Integer.parseInt(s);
            isValidInteger = true;
           // if (isValidInteger = true)
                searchid = i;
        }
        catch (NumberFormatException ex)
        {
            choice = s.charAt(0);
        }

       if (choice != 'x') {
            for (Person b:clients)
                if  (b.getId() == searchid){
                    exists = true;
                    giveStops(b);

                 }

                 if(exists == false) {

                System.out.println("  No such client");
                resartTheSiv();
            }
        }

    }

    public void resartTheSiv(){
     theSiv();
    }

    public int giveStops(Person i) {

        String input;
        System.out.println("    Trip:  ");
        input = In.nextLine();
        String[] split = input.split(" +");
        int start = Integer.parseInt(split[0]);
        int stop = Integer.parseInt(split[1]);
        i.setStart(start);
        i.setOff(stop);

       i.addPassenger(i); `// !! Here is where I try to add the selected instance of Person to car by first calling a method in Person to send itself to the passenger linked list.`
        resartTheSiv();
        return start;
    } 

    public void getClient() {
        System.out.print("  CarManager id: ");  
        char choice;
        int searchid = In.nextInt();

        boolean exists = false;

        while ((choice = In.nextChar()) !='x' ){
            for (Person i:clients)
                if  (i.getId() == searchid){
                    exists = true;
                    System.out.println("found client");
            }

            if (exists == false)
                System.out.println("  No such client");

        }

    }

    public  Person createPerson()
    {
        String name = readName();

        Person p = new Person(name, id++);
        System.out.println("  Hi " + p.getName() + ", " + "you are CarManager" + p.getId());
        return p;

    }

    private  String readName() {
        System.out.print("  Name: ");
        return In.nextLine();
    }

    public void showClients() {

        for (Person i: clients)
            System.out.println(i);

    }

}

这里是根 class,那里是 运行 来自

的程序
import java.io.*;

public class Root
{   public Root() {

        new CarManager();

    }

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

    private CarManager carManager;
}

这里是处理输入的地方,如果这也有帮助的话

import java.util.*;

public class In
{   private static Scanner in = new Scanner(System.in);

    public static String nextLine()
    {   return in.nextLine(); }

    public static char nextChar()
    {   return in.nextLine().charAt(0); }

    public static int nextInt()
    {   int i = in.nextInt();
        in.nextLine();
        return i;   }

    public static double nextDouble()
    {   double d = in.nextDouble();
        in.nextLine();
        return d;   }
}

直接给乘客打电话 .add 怎么样?无需构造新的 Person 对象或以任何方式设置 passengers 的值。

public void AddPassenger(Person newpassenger) {  
    passengers.add(newpassenger); 
}

另外一个小提示——通常方法名是驼峰式的,所以最好调用方法 addPassenger 而不是 AddPassenger

这是应用程序编程吗?

如果是这样,您的做法就完全错误了,因为您需要使用的是船而不是汽车!