0

I'm making a program to simulate patients and the severity of their illness.

I'm having trouble with adding different instances of one class to another class.

For some reason, when I use a while loop, it ultimately only makes one instance.

Here is my code:

 while(myScan.hasNext()){

      String line = myScan.nextLine();
      String [] storage = line.split(",");
      int severity = Integer.parseInt(storage[1]);

      Patient x = new Patient(storage[0],severity);
      Priority.add(x);

      }

When I make each instance separately and print my "Priority" class, it works fine. But when using the while loop, it only prints out the last instance, as if it is getting overwritten.

For Example:

Patient p1 = new Patient(name1,1);
Patient p2 = new Patient(name2,2);
Patient p3 = new Patient(name3,3);

This will work fine. but not when using the while loop to read from a file. It will only print p3.

4

2 回答 2

0

I cant see Priority defined as a storage (array/linkedList). So you need create variable to store Patient instances of the data.

ArrayList<Patient> items = new ArrayList<Patient>();
while(myScan.hasNext()){

  String line = myScan.nextLine();
  String [] storage = line.split(",");
  int severity = Integer.parseInt(storage[1]);

  Patient x = new Patient(storage[0],severity);
  items.add(x);

  }

Now items should contain created patients. I hope it is Java :D

于 2013-07-14T22:06:05.687 回答
0

I think that's because you are not iterating over your structure. You are just using the same Patient x over and over again.

You should use Lists or a Patient-Array to create your different Patients.
Or do you use Priority for that? If yes you should be able to get your different Patients out of this "List".

Edit: Example:

LinkedList<Patient> listOfPatients = new LinkedList<>();
while(myScan.hasNext){
    .
    .
    .
    Patient x = ... ;
    listOfPatients.add(x);
}
Patient p1=listOfPatients.getAt(0);
Patient p2=listOfPatients.getAt(1);
.
.
.

Just a simple example. I hope it helps.

于 2013-07-14T22:06:11.610 回答