need help converting this c code to java (short)

Associate
Joined
21 May 2003
Posts
1,008
Hi. I need to work out how to write the following in java:
Code:
struct times {
    int time ;
    char c ;
  } input_data[ NINPUT_DATA ] ;

so far I have:
Code:
public class times{
		int time;
		char c;
	} ;
	public times[] input_data  = new times[NINPUT_DATA];

but when i try and access something (i.e t.input_data.time), i get an error NullPointerException.

anyone have any ideas?
 
At the moment you are creating a new array of type times NINPUT_DATA elements long but not initialising any of the elements. They are all still null hence the NullPointerException.

To start with your times class needs a constructor so it knows how to build itself. You could also do with changing the name to something non plural as the object will only hold a single time.

Code:
public class times {
	private int time;
	private char c;

	//constructor
	public times(int time, char c) {
		this.time = time;
		this.c = c;
	}

	public int getTime() {
		return time;
	}

	//whatever other accessors or methods you want
}

Then to populate and use your datastructure
Code:
times[] input_data = new times[NINPUT_DATA];

for (int i=0; i<NINPUT_DATA; i++) {
	int time = //wherever this info comes from
	char c = //wherever this info comes from

	input_data[i] = new times(time, c);
}

//get the first element
times tmp = input_data[0]

//get the time of the 5th element
int tmp = input_data[4].getTime();
 
ok, that has sorted a lot out, but i really don't like the for look that initialises all the data. say if i want to initialise them all to 0, can i do :

Code:
//constructor
	public times() {
		this.time =0 ;
		this.c = 0;
	}

so that way at the beginning when it makes them all, it puts 0 in all of them?

or should i change it to:
Code:
private int time = 0;
	private char c = 0;
 
Both would work.

It is best to use your constructors to create a valid object. You can call one constructor from another to reduce code repetition.

Code:
//default constructor
public times() {
	this(0,'0');
}

You'll still need the loop to initialise all the elements though now you can just do input_data = new times();
 
Back
Top Bottom