Adding objects to an array - java

I have been looking at questions of how to add elements to an array How can I dynamically add items to a Java array?.
I do not understand how to add objects of a class type, not a datatype like String. How am I supposed to do this, when the object patient has various datatypes? What I can't get my head around, is how to put the attributes of a Patient object into an array.
Class Patient{
public Patient(String ptNo, String ptName, int procType) throws IOException
{
Patient.patientNo = ptNo;
Patient.patientName = ptName;
Patient.procedureType = procType;
}
}
Another class:
public static void main(String[] args) throws IOException
{
Patient [] patients;
Patient p = new Patient(null, null, 0);
int i = 0;
for (i = 0; i < 2; i++)
{
patients.add(p);
}
}
I understand I am missing the obvious, and only come here, after exhausting other resources.

You need to specify the array size like below
Patient [] patients = new Patient[2];
Then now add the elements like below
patients[i] = new Patient(null, null, 0)
The complete code like below
for (int i = 0; i < 2; i++)
{
patients[i] = new Patient(null, null, 0);
}

You need to access an array using the indexes
patients[i] = p;
but before that you need to initialize it as well.
Patient [] patients = new Patient[10]; // random init
Since you want them to be dynamic, try to use an ArrayList and keep adding the objects to it.
List<Patient> patients = new ArrayList<>();
patients.add(p);

Arrays are accessed via index:
Please modify your code like this.
public static void main(String[] args) throws IOException
{
Patient [] patients = new Patient[10];
Patient p = new Patient(null, null, 0);
int i = 0;
for (i = 0; i < 2; i++)
{
patients[i] = p;
}
}

You are using an array and not an ArrayList thus add them by specifying the index
for (i = 0; i < 2; i++)
{
patients[i] = p;
}
EDIT
If you really want to assign the same object in the string you can even skip the object reference, like
public static void main(String[] args) throws IOException
{
Patient [] patients = new Patient[2];
int i = 0;
for (i = 0; i < 2; i++)
{
patients[i] = new Patient(null, null, 0); // No need for p now
}
}

First you need to initialize an array to be of a specific size.
Patient [] patients = new Patient[2];
Secondly, you need to use index when assigning a value.
patients[i] = p;
Finally;
public static void main(String[] args) throws IOException
{
Patient [] patients = new Patient[2];
for (int i = 0; i < patients.length; i++)
{
patients[i] = new Patient(null, null, 0);
}
}

First:
Some fixes:
class Patient
{
public String patientNo;
public String patientName;
public int procedureType;
public Patient(String ptNo, String ptName, int procType)
{
this.patientNo = ptNo;
this.patientName = ptName;
this.procedureType = procType;
}
}
Since you want your patients to be unique not the same as Patient.sth is class' property (common to all instances).
Now array and inserting:
Patient patients[] = new Patient[2];
for (int i = 0; i < patients.length; i++)
{
patients[i] = new Patient(null, null, 0);
}
but again do not fill array with the same objects. In addition not to be bound to fixed array size - use Vector (for example)
Update: about class members / aka static object members
These 2 code samples are completely different things:
class X
{
public String abc;
public void someMember()
{
this.abc = ;
}
}
and
class X
{
public static String abc;
public void someMember()
{
X.abc =
}
}
You must distinguish between what is unique to an abject and what is common to a class (ie available to all instances - common to them).
With static keyword you declare class members (they will be common foa all instances). You cannot use them with 'this' keyword which is reserved for instance members from the first example.
Here is what you must read class vs instance members

Related

get an object based on its static value

I am initalizing several objects of the same type that have a common field:
public class Example {
private static objectCounter = 1;
public Example () {
objectCounter++;
}
}
Since these objects are created with a for loop like this
for (int i = 0; i<5; i++) {
Example e = new Example();
}
they are not referenced.
Is there a way to get a specific object based on objectCounter value ?
Something like
//get the Example object with objectCounter==2
get(2);
Thank you
My suggestion will be saving into array:
Example store[] = new Example[5]
for (int i = 0; i<5; i++) {
store[i] = new Example();
}
And then , search for the specific object.
As stated in the comments, a static value will persist through all instances of your class.
If you want your Example to "know" it's identity, pass it in when you construct it:
Example:
public class Example {
private int id;
public Example (int val) {
this.id = val;
}
// Getters/setters
}
Probably also want to add your objects to a list to access them later, so before your for-loop:
List<Example> examples = new ArrayList()<Example>;
And create them like this:
for (int i = 0; i<5; i++) {
Example e = new Example(i);
examples.add(e);
}

how to call a method through a 2d array error

I'm trying to create a new list so that whatever the user enters into the altitude this method should look for the coordinates and return the coordinates below what user has entered. I'm struggling to get this method to run.
static double[][] array;
Map m = new Map();
public static void main(String[] args) throws FileNotFoundException {
m.coordinatesBelow(-2000)
}
public static void readDataArray(String filename) throws FileNotFoundException {
Scanner input = new Scanner(new BufferedReader(new FileReader("sample.xyz")));
int rows = 2500000;
int columns = 3;
double[][] array= new double[rows][columns];
int i = 0;
while (input.hasNextLine()) {
String[] line = input.nextLine().trim().split("\t");
for (int j = 0; j < line.length; j++) {
array[i][j] = Double.parseDouble(line[j]);
}
i++;
}
System.out.println(Arrays.deepToString(array));
}
public List<Double> coordinatesBelow(double altitude) {
List<Double> coordinatesBelow = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
coordinatesBelow.add(array[i][2]);
}
coordinatesBelow.removeIf(b -> b > altitude);
return coordinatesBelow;
}
Your static double[][] array; declared at the first line and double[][] array = new double[rows][columns]; are 2 different variables: the first is static, the second is local. So when you read the values into the local array the static one remains empty.
If you want to save the values into the static array, don't create a new variable, just initialize the static array in your static method - change
double[][] array = new double[rows][columns];
to
array = new double[rows][columns];
UPD: If you are getting a NullPointerException at the line for (int i = 0; i < array.length; i++), the only thing that can be null here is array. So make sure the array is initialized before you call coordinatesBelow. And you initialize it in the readDataArray method, so try calling it first:
public static void main(String[] args) throws FileNotFoundException {
readDataArray("filename.txt");
m.coordinatesBelow(-2000);
}
Bu the way, it looks like the filename argument is not used anywhere, so you can remove it.
You're calling coordinatesBelow as a method of Map. Is this correct? This would need to be a class that you have created yourself like so:
private static class Map {
public List<Double> coordinatesBelow(double altitude) {
List<Double> coordinatesBelow = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
coordinatesBelow.add(array[i][2]);
}
coordinatesBelow.removeIf(b -> b > altitude);
return coordinatesBelow;
}
}

Printing on same line

I am new to Java and I am trying to print the student numbers and numbers (cijfer in this case) on 1 line. But for some reason I get weird signs etc. Also when I'm trying something else I get a non-static context error. What does this mean and how does this exactly work?
Down here is my code:
import java.text.DecimalFormat;
import java.util.Arrays;
public class Student {
public static final int AANTAL_STUDENTEN = 50;
public int[] studentNummer = new int[AANTAL_STUDENTEN];
public String[] cijfer;
public int[] StudentNummers() {
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
studentNummer[i] = (50060001 + i);
}
return studentNummer;
}
public String[] cijfers(){
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
DecimalFormat df = new DecimalFormat("#.#");
String cijferformat = df.format(Math.random() * ( 10 - 1 ) + 1);
cijfer[i++] = cijferformat;
}
return cijfer;
}
public static void main(String[] Args) {
System.out.println("I cant call the cijfer and studentnummer.");
}
}
Also I'm aware my cijfer array is giving a nullpointer exception. I still have to fix this.
I am not java developer but try
System.out.print
You could loop around System.out.print. Otherwise make your functions static to access them from main. Also initialize your cijfer array.
Besides the things I noted in the comments, your design needs work. You have a class Student which contains 50 studentNummer and cijfer members. Presumably, a Student would only have one studentNummer and and one cijfer. You need 2 classes: 1 for a single Student and one to hold all the Student objects (StudentBody for example).
public class StudentBody {
// An inner class (doesn't have to be)
public class Student {
// Just one of these
public int studentNummer;
public String cijfer;
// A constructor. Pass the student #
public Student(int id) {
studentNummer = id;
DecimalFormat df = new DecimalFormat("#.#");
cijfer = df.format(Math.random() * ( 10 - 1 ) + 1);
}
// Override toString
#Override
public String toString() {
return studentNummer + " " + cijfer;
}
}
public static final int AANTAL_STUDENTEN = 50;
public Student students[] = new Student[AANTAL_STUDENTEN];
// StudentBody constructor
public StudentBody() {
// Create all Students
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
students[i] = new Student(50060001 + i);
}
}
// Function to print all Students
public void printStudents(){
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
System.out.println(students[i]);
}
}
public static void main(String[] Args) {
// Create a StudentBody object
StudentBody allStudents = new StudentBody();
// Print
allStudents.printStudents();
}
}
Just make all your methods and class variables as static. And then you have access to them from main method. Moreover you have got some errors in code:
public class Student {
public static final int AANTAL_STUDENTEN = 50;
// NOTE: static variables can be moved to local ones
// NOTE: only static method are available from static context
public static int[] StudentNummers() {
int[] studentNummer = new int[AANTAL_STUDENTEN];
for (int i = 0; i < AANTAL_STUDENTEN; i++)
studentNummer[i] = 50060001 + i;
return studentNummer;
}
// NOTE: only static method are available from static context
public static String[] cijfers() {
// NOTE: it is better to use same `df` instance
DecimalFormat df = new DecimalFormat("#.#");
String[] cijfer = new String[AANTAL_STUDENTEN];
for (int i = 0; i < AANTAL_STUDENTEN; i++)
// NOTE: remove `i++`, because we have it in the loop
cijfer[i] = df.format(Math.random() * (10 - 1) + 1);
return cijfer;
}
// NOTE: this is `static` method, therefore it has access only to static methods and variables
public static void main(String[] Args) {
String[] cijfer = cijfers();
int[] studentNummer = StudentNummers();
// TODO you can pring two arrays one element per line
for(int i = 0; i < AANTAL_STUDENTEN; i++)
Sytem.out.println(cijfer[i] + '-' + studentNummer[i]);
// TODO as alternative, you can print whole array
System.out.println(Arrays.toString(cijfer));
System.out.println(Arrays.toString(studentNummer));
}
}

Using an array as an attribute to modify it Java

my friend has programmed a Breakout game in java. I know C++, which tranfers relatively well to java.
I had a problem when trying to insert a MultiBall brick.
Here are the relevent bits of my function:
private Balle[] balle;
public BriqueMultiBalle(Balle[] bal) {
super();
balle = bal;
SCORE = 100;
}
public void touched() {
visible = false;
balle[Balle.getNInstance()].makeVisible();
}
I get no error but I found out when debugging that balle corresponds to a null pointer. I tried using these different declarations, however, none of them worked:
1.
public BriqueMultiBalle(Balle[] bal) {
super();
for(int i = 0; i < 6; i++)
{
balle[i] = bal[i];
}
SCORE = 100;
}
2.
public BriqueMultiBalle(Balle[] bal) {
super();
balle = new Balle[](bal);
SCORE = 100;
}
However, these methods do not work.
Thanks,
Ghi102
You are getting a null pointer on balle because you never initialize the array, you leave it as
private Balle[] balle;
Try initializing you code
balle = new Balle[bal.length];
for(int i = 0; i < bal.length; i++){
balle[i] = bal[i];
}
Here's an example I wrote using an int array. Same concept, just apply it to your object.
public static void main(String[] args) throws Exception {
int[] arrayInts;
int[] originalInts = { 1, 2, 3, 4, 5 };
arrayInts = new int[originalInts.length];
for(int i = 0; i < originalInts.length; i++){
arrayInts[i] = originalInts[i];
}
originalInts[0] = 10;
for (int i : arrayInts) {
System.out.println(i);
}
}

Why is there an NullPointerException?

I am trying to mommertary use a string and convert it to an int to compare the first first column and all the rows with the all of the numbers within the string typed in. When I type in a number, I get a NullPointerException. The thing is, I don't understand why the compiler is telling me this when I feel like I have declared all my objects properly. please help!
import java.util.ArrayList;
public class Decoder
{
private int[][] zipdecoder;
private ArrayList<Integer> zipcode;
private String finalCode;
private String bars;
private int place;
public Decoder()
{
int[][] zipdecoder = new int[][]{
{1,0,0,0,1,1},
{2,0,0,1,0,1},
{3,0,0,1,1,1},
{4,0,1,0,0,0},
{5,0,1,0,1,1},
{6,0,1,1,0,0},
{7,1,0,0,0,0},
{8,1,0,0,1,1},
{9,1,0,1,0,0},
{0,1,1,0,0,0}
};
zipcode = new ArrayList<Integer>();
}
public void insertToArray(String zip)
{
int count = 0;
for(int i = 1; i<zip.length()+1;i++)
{
String piece = zip.substring(count, i);
int number = Integer.parseInt(piece);
for(int j = 0;j<10;j++)
{
if(number == zipdecoder[j][0]){
for(int a = 1;a<5;a++)
{
zipcode.add(place,zipdecoder[j][a]);
place++;
}
}
count++;
}
}
}
You're not initializing the class member zipdecoder but a new local variable (with the same name) in the constructor.
Change this
int[][] zipdecoder = new int[][]{
to
zipdecoder = new int[][]{
and it should work.

Categories

Resources