Adding objects to an Array in a class from a test file? - java

Unsure on how i'm supposed to add to an array, i've been asked to fill the array from a test file but define it in class Patient. Any ideas?
public class Patient
{
private String name;
private int id;
private int current = 1;
public Patient(String name, int id)
{
this.name = name;
this.id = id;
Patient[] patient = new Patient[100];
String[] Observations;
System.out.print(patient[0]);
}
public String addPatient(String name,int id)
{
Patient[current-1] = new Patient(name,id);
}
}
// extract from class PatientRecordSystem
public void addPatient()
{
String name = "James";
int id = 10122;
Patient patient = new Patient(name, id);
}

Your problem is that you are defining that list (or array) to hold Patient objects within the constructor of your Patient class.
That is simply wrong on many levels. First of all - one "Patient" should be exactly that - the representation of a single patient. When you go to the doctor and become a patient ... are you asked to know about 100 other patients around?! Then: that array that you define in the constructor ... just lives during the execution of the constructor. It simply goes away as soon as a call
Patient newPatient = new Patient( ... )
returns.
In other words: you want to think of another class that is responsible for "managing" multiple patients. And then you create "patient objects"; and tell the manager about them. And that "manager" is then using an array (or better some more dynamic List) in order to keep track of "managed" patients.

Whatever Andrew said is correct , just making it easy for you. Use below code
public class Patient
{
private String name;
private int id;
private int current = 1;
private Patient[] patient = new Patient[100];
public Patient(String name, int id)
{
this.name = name;
this.id = id;
String[] Observations;
System.out.print(patient[0]);
}
public String addPatient(String name,int id)
{
patient[current-1] = new Patient(name,id);
}
}
// extract from class PatientRecordSystem
public void addPatient()
{
String name = "James";
int id = 10122;
Patient patient = new Patient(name, id);
}

First you need to declare the array.
You can do something like:
Patient[] patients = new Patient[100];
if you know the size of the array.
If you want to build a dynamic array, because you don't know how many elements you are going to have, you can do something like that.
List<Patient> patients = new ArrayList<Patient>();
Then you can assign values to the array:
If you have declared a fixed array you can do something like that:
patients[0] = new Patient(name, id);
On the other hand, if you have declared a dynamic array, the code would look like:
patients.add(new Patient(name, id));

Related

How to change array to an object class?

I have cut out the code to shorten the page but I'm asking how do I change personInterests into its own class. Apologies for the vague question but essentially I want to change personInterests in my Person class to a class where personInterests has multiple variables.
import java.util.ArrayList;
import java.util.*;
public class Person{
private String personName;
private String[] personInterests = new String[3];
public Person(String personName, String[] personInterests){
this.personName = personName;
this.personInterests = personInterests;
}
public void setInterests(String[] personInterests){
this.personInterests = personInterests;
}
public String[] getInterests(){
return personInterests;
}
public String getName(){
return personName;
}
public String toString(){
String result = getName() + " ";
for (String interests : personInterests) {
result += interests + " ";
}
return result;
}
}
This was my idea of how it would work just not sure how I would use this class and call it later on.
import java.util.ArrayList;
import java.util.*;
public class Interests {
private int interestDangerRating;
private String interestName;
private ArrayList<Interests> interestsList = new ArrayList<>();
public Interests (int interestDangerRating ,String interestName){
this.interestDangerRating = interestDangerRating;
this.interestName = interestName;
}
public void addInterests(Interests p){
interestsList.add(p);
}
Interests getInterests(int i){
return interestsList.get(i);
}
}
Any help is appreciated, as I said this code has mostly been taken out and this was an old project already completed just wanted to see if I could change some of the features.
OK so here's what I would do to clean this up for you and make it work. Firstly, think about what you are trying to do. You want to create a Person who has multiple Interests, right? So the Interest class, going by your above example, can be changed to be a typical Java object class as follows:
public class Interest {
private int dangerRating;
private String name;
public Interest (int dangerRating, String name) {
this.dangerRating = dangerRating;
this.name = name;
}
public int getDangerRating() {
return dangerRating;
}
public String getName() {
return name;
}
}
So now we've an Interest class set up where you can set a name for your interest and a danger rating. What we need to do, now, is edit your Person class so as you can store a list of interests for each Person you create.
import java.util.ArrayList;
public class Person{
private String name;
private ArrayList<Interest> interests = new ArrayList<Interest>();
public Person(String name, ArrayList<Interest> interests) {
this.name = name;
this.interests = interests;
}
public void addInterest(Interest newInterest) {
interests.add(newInterest);
}
public Interest getInterest(int indexOfInterest) {
return interests.get(indexOfInterest);
}
public ArrayList<Interest> getInterests() {
return interests;
}
public String getName() {
return name;
}
public String toString() {
String result = getName() + " ";
for(Interest interest : interests) {
result += interest.getName() + "(" + interest.getDangerRating() + ")" + " ";
}
return result.trim();
}
}
This allows you to set an initial list of all interests for your new Person and, from there, you can add new interests, get all interests or get any individual interest.
Hope this helps to clarify for you how this should all fit together!
So now it's time to instantiate everything. Lets create some Interestobjects which we will use:
Interest golf = new Interest(1, "golf");
Interest swimming = new Interest(3, "swimming");
Now lets assume we want two people called John and Mary. John likes golf and swimming while Mary only likes swimming. We'd then create their list of Interest as follows:
ArrayList<Interest> johnsInterests = new ArrayList<Interest>();
johnsInterests.add(golf);
johnsInterests.add(swimming);
ArrayList<Interest> marysInterests = new ArrayList<Interest>();
marysInterests.add(swimming);
And finally, we'd then create our two Person objects which will include the persons name and interests list.
Person john = new Person("John", johnsInterests);
Person mary = new Person("Mary", marysInterests);
And voila!
First, make an Interestclass:
public class Interest {
private int interestDangerRating;
private String interestName;
// .. getters and setters
}
then in the Personclass get rid of private String[] personInterests = new String[3];
and replace it by:
private ArrayList<Interest> interestsList = new ArrayList<>();
You're getting there with the logic of your Interests class, but it needs a few changes
import java.util.ArrayList;
import java.util.*;
public class Interests {
private int interestDangerRating;
// Is this a unique name for the entire class? If yes then no worries, but if not
// then its not needed, you've already got a list of interest names below
private String interestName;
// Change the array list to hold Strings, it's a list of words
private ArrayList<String> interestsList = new ArrayList<>();
public Interests (int interestDangerRating ,String interestName){
this.interestDangerRating = interestDangerRating;
this.interestName = interestName;
}
public void addInterest(String p){ // Again, change this to String
interestsList.add(p);
}
String getInterest(int i){ // Change this to return a String, since we changed the ArrayList above
return interestsList.get(i);
}
}
There's alot more you need to think about with this class too. How do you know how many interests are in the list, should there be a length variable? Or what about a method that returns the entire list of interests rather than just 1?
Also, there's only one interestDangerRating being set in this class; if each interest has a different danger rating, should't you be adding a danger rating for every interest?
In terms of accessing your new class, you'll need to create a class in your code by:
Interests variableName = new Interests(1, "football");
I have randomly chosen '1' and 'football' above, since they are in your Interest class' constructor. The way your class is built, you cannot use it without providing an int and a String when the object is made
Finally, to call methods on your class, you use the variable created above to call its methods:
variableName.addInterest("basketball");
String interest = variableName.getInterest(1);
If you're struggling, I recommend looking at a simple java tutorial online. instatiating java classes and calling their methods like this are fundamental concepts in Java :)

Having troubles creating this object

I'm very new to java, and trying to grasp making an object with two different values.
I'm trying to create a Customer object called customer, with the initial values of 1 and cust1, and then display the customer object to the output with toString()
Thanks for any help in advance.
Here's what I have currently.
public class Customer {
private int id;
private String name;
public Customer(int id, String name) {
this.id = id;
this.name = name;
Customer customer = new Customer(1, "cust1");
}
You have no entry point to your program, which should look like this in your class
public static void main(String[] args)
{
//objects created here
}
You also create a Customer object as a member of your Customer class which means every Customer object contains another.
You can't set Customer members like this
Customer customer = new Customer(); //you also don't have a no argument constructor
customer = 1; //how would it know where to put this 1?
customer = cust1; //same as above
it would be like this (if they were in the right place, as mentioned above)
Customer customer = new Customer(); //if using this method you will need a no argument constructor
customer.id = 1;
customer.name = cust1;
or like this
new Customer(1,"cust1");
In Summary
You need an entry point
You are creating Customer with a no argument constructor but you only have one constructor which has two arguments
You are -for some reason- creating a Customer inside every Customer
You are not setting members of your Customer object in the correct (or even in a valid) way
Don't create a new object instance within a classes constructor — this will result in a StackoverFlowException.
public class Customer {
private final int id;
private final String name;
public Customer(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
In a separate class you can simply create a new instance by using
Customer customer = new Customer(1, "Name");

Java, How do i use add a string and an integer to an array

This is the array code I have so far:
ArrayList<Data> arrl = new ArrayList<Data>();
arrl.add("Tim", 23);
Need to know how to an integer and a string to the array.
For Example:
names: and ages:
Tim 23
Max 56
Clare 43
I know how to add integers OR strings to array-lists but i can't figure how to incorporate both in the same array.
Your list is taking objects of type Data. So, create a Data class that contains a String for the name and int for the age. Create a Data object for each entry you want and add it to your arrl list.
public class Data {
private String name;
private int age;
/**
* Constructor
*/
public Data(String name, int age) {
this.name = name;
this.age = age;
}
// Getters and Setters go here.
}
In this example I used a constructor to allow easy construction of a Data object with a name and age.
List<Data> arrl = new ArrayList<Data>();
arrl.add(new Data("Tim", 23));
You could have a class Person for instance, where you save the name and age of a person.
Then, you have a ArrayList of Person, and you can store and access that information.
ArrayList is a class that use generics, it means type-safety, so when you declare a class that use generic in its class definition you have to declare the type when making the instance.
If you want to store Stringobjects declare ArrayList in this way:
ArrayList<String> saveString = new ArrayList<String>
You can make a class Person with those instance variables and resolve your problem.
For example:
public class Person {
private String name;
private int age;
public Person(String name,int age){
this.name = name;
this.age = age;
}
}
And then you can use in this way:
ArrayList<Person> people = new ArrayList<Person>();
people.add(new Person("Luis Alberto",15));
Your arraylist is made for Data objects that means you have to create Data object to put it there, `this is what i mean by that arrl.add(new Data("Tim",44));
Make sure that you have class Data with constructor for string and int
Something like this:
public class Main {
public static void main(String[] args) {
ArrayList<Person> arrl = new ArrayList<>();
arrl.add(new Person("Tim", 23));
}
}
class Person {
private String name;
private int age;
Person (String name, int age) {
this.name = name;
this.age = age;
}
}
I think the best approach is what is proposed by Wabs and Ashot Karakhanyan. But if your need, is to have the name and age as different items of your list, you can use the following:
List<Object> arrl = new ArrayList<Object>();
arrl.add("name");
arrl.add(23);

Java arraylist incompatible types error

The answer to this will probably turn out to be obvious in retrospect but for now I find myself rather stuck on this. I'll give some blocks of code first and then present the problem.
This is part of my class Stockmanager, I have omitted some methods that have nothing to do with this problem.
import java.util.ArrayList;
public class StockManager
{
private ArrayList stock;
public StockManager()
{
stock = new ArrayList();
}
public void addProduct(Product item)
{
stock.add(item);
}
public Product findProduct(int id)
{
int index = 0;
while (index < stock.size())
{
Product test = stock.get(index);
if (test.getID() == id)
{
return stock.get(index);
}
index++;
}
return null;
}
public void printProductDetails()
{
int index = 0;
while (index < stock.size())
{
System.out.println(stock.get(index).toString());
index++;
}
}
}
Here's my class Product, again with some methods omitted.
public class Product
{
private int id;
private String name;
private int quantity;
public Product(int id, String name)
{
this.id = id;
this.name = name;
quantity = 0;
}
public int getID()
{
return id;
}
public String getName()
{
return name;
}
public int getQuantity()
{
return quantity;
}
public String toString()
{
return id + ": " +
name +
" voorraad: " + quantity;
}
}
My problem lies in the fact that I get a compile time error in the findProduct() method. To be more specific the line Product test = stock.get(index); is indicated with a message incompatible types.
The constructor of StockManager creates a new ArrayList with the name stock. As is evident from the method addProduct() this ArrayList contains items of the type Product. The Product class has a number of variables one of which is called id and is of type integer. That class also contains a method getID() that returns an id.
As far as I know, the way of getting an item from an arraylist is the get() method with the number between the () indicating the item's position. Seeing as my arraylist contains instances of Product, I expect to get a Product as result when I use the get() method on the arraylist. So I don't understand why it doesn't work when I define a variable called test of the type Product and try to assign an item from the arraylist to it. I have as far as I know, successfully used this same technique in the method printProductDetails() where I use the toString() method from Product on the object from the arraylist.
I hope someone will be able to clarify for me where I am at fault. If it makes any difference, I am doing this stuff in BlueJ which is probably not the best tool for it but it is the one I'm supposed to use for this school project.
private ArrayList stock;
You should redeclare this with a bounded type like so:
private List<Product> stock = new ArrayList<Product>();
If you don't, this line:
Product test = stock.get(index);
won't work because you're trying to assign a raw Object to a Product.
Others have suggested casting the Object to a Product, but I wouldn't recommend this.
Your stock is defined as private ArrayList stock, which means that stock.get() returns an Object without any special type. You should either make Stock an ArrayList of Products
ArrayList<Product> stock;
or cast the result of the get method manually
Product test = (Product)stock.get(whatever);
Product test = (Product) stock.get(index);
or if you make your list List<Product> stock your line should work without changes.

ArrayList - How to modify a member of an object?

I have a number of Customer objects stored in an ArrayList. My Customer class has 2 data members: Name and Email. Now I want to modify just the Email for Customer "Doe".
Now if "Doe" is located at index 3 in the list, I know I can write this line:
myList.set( 3, new Customer( "Doe", "j.doe#supermail.com" ) );
But that means creating a new object. If I have a very big list, I suppose the process would be very slow. Is there any other way to directly access the data member of an Object stored in an ArrayList, maybe by using another kind of Collection than ArrayList?
You can do this:
myList.get(3).setEmail("new email");
Fixed. I was wrong: this only applies on element reassignment. I thought that the returned object wasn't referencing the new one.
It can be done.
Q: Why?
A: The get() method returns an object referencing the original one.
So, if you write myArrayList.get(15).itsVariable = 7or myArrayList.get(15).myMethod("My Value"),you are actually assigning a value / using a method from the object referenced by the returned one (this means, the change is applied to the original object)
The only thing you can't do is myArrayList.get(15) = myNewElement. To do this you have to use list.set() method.
You can iterate through arraylist to identify the index and eventually the object which you need to modify. You can use for-each for the same as below:
for(Customer customer : myList) {
if(customer!=null && "Doe".equals(customer.getName())) {
customer.setEmail("abc#xyz.com");
break;
}
}
Here customer is a reference to the object present in Arraylist, If you change any property of this customer reference, these changes will reflect in your object stored in Arraylist.
Assuming Customer has a setter for email - myList.get(3).setEmail("j.doe#supermail.com")
I wrote you 2 classes to show you how it's done; Main and Customer. If you run the Main class you see what's going on:
import java.util.*;
public class Customer {
private String name;
private String email;
public Customer(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return name + " | " + email;
}
public static String toString(Collection<Customer> customers) {
String s = "";
for(Customer customer : customers) {
s += customer + "\n";
}
return s;
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Customer> customers = new ArrayList<>();
customers.add(new Customer("Bert", "bert#gmail.com"));
customers.add(new Customer("Ernie", "ernie#gmail.com"));
System.out.println("customers before email change - start");
System.out.println(Customer.toString(customers));
System.out.println("end");
customers.get(1).setEmail("new.email#gmail.com");
System.out.println("customers after email change - start");
System.out.println(Customer.toString(customers));
System.out.println("end");
}
}
to get this running, make 2 classes, Main and Customer and copy paste the contents from both classes to the correct class; then run the Main class.
Use myList.get(3) to get access to the current object and modify it, assuming instances of Customer have a way to be modified.
You can just do a get on the collection then just modify the attributes of the customer you just did a 'get' on. There is no need to modify the collection nor is there a need to create a new customer:
int currentCustomer = 3;
// get the customer at 3
Customer c = list.get(currentCustomer);
// change his email
c.setEmail("somethingelse#example.com");
Well u have used Pojo Entity so u can do this.
u need to get object of that and have to set data.
myList.get(3).setEmail("email");
that way u can do that. or u can set other param too.
If you need fast lookup (basically constant time) of a object stored in your collection you should use Map instead of List.
If you need fast iteration of the objects you should use List.
So in your case...
Map<String,Customer> customers = new HashMap<String,Customer>();
//somewhere in the code you fill up the Map, assuming customer names are unique
customers.put(customer.getName(), customer)
// at some later point you retrieve it like this;
// this is fast, given a good hash
// been calculated for the "keys" in your map, in this case the keys are unique
// String objects so the default hash algorithm should be fine
Customer theCustomerYouLookFor = customers.get("Doe");
// modify it
theCustomerYouLookFor.setEmail("newEmail#stackoverflow.com")
Without function here it is...it works fine with listArrays filled with Objects
example
`
al.add(new Student(101,"Jack",23,'C'));//adding Student class object
al.add(new Student(102,"Evan",21,'A'));
al.add(new Student(103,"Berton",25,'B'));
al.add(0, new Student(104,"Brian",20,'D'));
al.add(0, new Student(105,"Lance",24,'D'));
for(int i = 101; i< 101+al.size(); i++) {
al.get(i-101).rollno = i;//rollno is 101, 102 , 103, ....
}
Any method you use, there will always be a loop like in removeAll() and set().
So, I solved my problem like this:
for (int i = 0; i < myList.size(); i++) {
if (myList.get(i).getName().equals(varName)) {
myList.get(i).setEmail(varEmail);
break;
}
}
Where varName = "Doe" and varEmail = "j.doe#supermail.com".
I hope this help you.
Try this.This works while traversing the code and modifying the fields at once of all the elements of Arraylist.
public Employee(String name,String email){
this.name=name;
this.email=email;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
for(int i=0;i++){
List.get(i).setName("Anonymous");
List.get(i).setEmail("xyz#abc.com");
}

Categories