2015-04-06 1 views
0

Je suis un programmeur java débutant et je rencontre un problème.Stockage d'instance de classe dans une autre classe en Java

J'ai marqué les zones clés du code avec '// !!', j'ai inclus le reste du programme pour faciliter le dépannage.

Je tente de stocker une instance de Person stockée dans les clients de la liste liée dans la classe Clients dans une liste liée appelée passagers dans une instance de la classe Car. Cependant, je rencontre constamment l'erreur ayant besoin de fournir une chaîne et int, deux valeurs stockées dans les objets Person. Je pensais cependant que parce que j'ai déjà sélectionné la classe Person, cela serait transféré? Est-ce que quelqu'un sait où je vais mal? En résumé, j'essaie de copier une instance d'un objet (Person) dans une liste chaînée (In clients) dans une autre liste liée des mêmes objets dans une autre classe (Car) qui est elle-même une instance (il y a 3 objets de voiture)

Toute aide est grandement appréciée.

est ici la voiture de classe qui contient les passagers liste chaînée

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. 

    } 

Voici la personne de classe

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

} 

Voici la classe CARMANAGER, il contient la liste chaînée d'objets de voitures.

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

    } 



} 

Voici la classe Clients, il contient les clients liste chaînée qui contient les instances de la personne que je veux ajouter à une instance de voiture

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

    } 

} 

Et voici la classe Root, il est où le programme est exécuté à partir

import java.io.*; 

public class Root 
{ public Root() { 

     new CarManager(); 

    } 

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

    private CarManager carManager; 
} 

Voici où est entrée traitée si cela aide également

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

Répondre

1

Que diriez-vous d'appeler .add sur des passagers? Pas besoin de construire un nouvel objet Person ou de définir la valeur des passagers de quelque façon que ce soit.

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

également une petite note - généralement des noms de méthode sont CamelCase, donc il serait préférable d'appeler la méthode addPassenger au lieu de AddPassenger

+0

excusez s'il vous plaît cette question si elle apparaît comme stupide, j'espérais simplement développer mes connaissances plus. La méthode compile si je l'annule, mais dans votre cas, vous avez fait que la méthode retourne une personne, mais je ne fais qu'ajouter à une liste chaînée, donc j'étais curieux de savoir ce que ça retournerait et si c'était nécessaire faire cela? – Mark

+0

Ah c'est une erreur. Cela devrait être nul – Mshnik

0

Est-ce pour la programmation d'application?

Si oui, vous le faites complètement faux que vous avez besoin d'utiliser un bateau PAS UNE VOITURE!