Google Groups unterstützt keine neuen Usenet-Beiträge oder ‑Abos mehr. Bisherige Inhalte sind weiterhin sichtbar.

Arrays

0 Aufrufe
Direkt zur ersten ungelesenen Nachricht

Michael

ungelesen,
10.03.2006, 13:54:4810.03.06
an
Hello all, its been awhile. Anyways, I had a question regarding arrays. Say
I want to create an array of 25objects, but I only end up filling the array
with 23 objects. I know I need a counter to keep track of the objects read
into the arrray. I have completed this but for some reason I am getting a
NullPointerException; does it have anything to do with once an array is
declared in size it can not be changed?

My code segment;

import java.io.*;

public class ReadTextFile {

public static void main(String[] args) {

Student [] stud = new Student[25];
String dataLine;
int i = 0;
int total = 0;


try{
FileReader inFile = new FileReader("students.txt");
BufferedReader ins = new BufferedReader(inFile);

dataLine = ins.readLine();


while(dataLine != null){

stud[i] = new Student();
stud[i].fillStudent(dataLine);
stud[i].findAverage();

total++;
i += 1;
dataLine = ins.readLine();
}
ins.close();
}
catch(NumberFormatException e){
System.out.println("Number Format error: " + e.getMessage());
e.printStackTrace();
}
catch(IOException e){
System.out.println("i/o error: " + e.getMessage());
e.printStackTrace();
}
try{
Sorts.selectionSort(stud);
for(i=stud.length-1;i>=0;i--){
System.out.println(stud[i].toString());
}
System.out.println();
System.out.println("The total number of students read = " + total);
}
catch(Exception e){
System.out.println("Other error: " + e.getMessage());
e.printStackTrace();
}
}
}


Oliver Wong

ungelesen,
10.03.2006, 14:26:5710.03.06
an

"Michael" <mbia...@shaw.ca> wrote in message
news:YXjQf.133228$B94.51075@pd7tw3no...

> Hello all, its been awhile. Anyways, I had a question regarding arrays.
> Say I want to create an array of 25objects, but I only end up filling the
> array with 23 objects. I know I need a counter to keep track of the
> objects read into the arrray. I have completed this but for some reason I
> am getting a NullPointerException; does it have anything to do with once
> an array is declared in size it can not be changed?
>
> My code segment;
>

Probably not. I'd expect something like ArrayIndexOutOfBoundsException
if you went beyond the edge of the array, but I see no opportunity for NPE
to show up from a quick cursory glance. You're correctly create a new
student for every entry in the array that you care about:

[most of the code snipped]


> public class ReadTextFile {
>
> public static void main(String[] args) {
>
> Student [] stud = new Student[25];

[...]


> while(dataLine != null){
>
> stud[i] = new Student();
> stud[i].fillStudent(dataLine);
> stud[i].findAverage();
>
> total++;
> i += 1;
> dataLine = ins.readLine();
> }

[...]
> }
> }

Can you save me the effort of a deeper investigation by giving the line
the NPE is thrown at?

- Oliver

Eric Sosman

ungelesen,
10.03.2006, 14:28:1310.03.06
an

Michael wrote On 03/10/06 13:54,:


> Hello all, its been awhile. Anyways, I had a question regarding arrays. Say
> I want to create an array of 25objects, but I only end up filling the array
> with 23 objects. I know I need a counter to keep track of the objects read
> into the arrray. I have completed this but for some reason I am getting a
> NullPointerException; does it have anything to do with once an array is
> declared in size it can not be changed?

Not exactly, although it's true that an array's size
cannot change. You're getting NullPointerException because
you've left a few slots of the array unfilled, meaning that
they're still set to null and do not refer to valid Students.
When you try to use one of those nulls to do something with
the Student it points to (or doesn't point to, rather), Java
slaps your wrist.

You might be able to fix this by running the final loop
from total-1 instead of from stud.length-1, but probably not:
Quite likely, the Sorts.selectionSort() method will trip over
the nulls at the end of the array. (That's not a sure thing;
I'm just guessing about what the method probably does.)

A better solution, which would allow you to handle both
less and more than twenty-five students, would be to abandon
the array and store the Student references in a data structure
that adapts its size automatically, like java.utils.ArrayList.

> My code segment;
> [snipped; see up-thread]

--
Eric....@sun.com

James Westby

ungelesen,
10.03.2006, 14:38:0710.03.06
an

It's not clear what the difference between these two variables is, they
seem to do the same thing. Remove i if that is the case.

> dataLine = ins.readLine();
> }
> ins.close();
> }
> catch(NumberFormatException e){
> System.out.println("Number Format error: " + e.getMessage());
> e.printStackTrace();
> }
> catch(IOException e){
> System.out.println("i/o error: " + e.getMessage());
> e.printStackTrace();
> }
> try{
> Sorts.selectionSort(stud);
> for(i=stud.length-1;i>=0;i--){

You have kept a count of the number of students, total, where total <=
stud.length, but here you use stud.length for the number of students.
Try replacing this with total.

> System.out.println(stud[i].toString());

You didn't say, but I assume this is where the NPE is thrown, it will
happen when i = 23 (if there are 23 students) as array entries are null
upon creation. (You should include the exact exception message and stack
trace and point out which line it is refering to in your post when you
are asking about an exception).

> }
> System.out.println();
> System.out.println("The total number of students read = " + total);
> }
> catch(Exception e){
> System.out.println("Other error: " + e.getMessage());
> e.printStackTrace();
> }
> }
> }
>
>

If you are sure there are never going to be more than 25 students then
this approach works fine. However if you are not sure look into
ArrayList, it grows the array for you, so you don't need to know
beforehand how many entries there will be.


James

Robert Waters

ungelesen,
10.03.2006, 14:39:1110.03.06
an
Based on a quick glance:

> while(dataLine != null){
>
> stud[i] = new Student();
> stud[i].fillStudent(dataLine);
> stud[i].findAverage();
>
> total++;
> i += 1;
> dataLine = ins.readLine();
> }

at end of this loop, i and total would have the number of student
records entered (hopefully it is less than 25 or you will get an exception
here when i=25 and you try to put another student in your fixed length
array.


> for(i=stud.length-1;i>=0;i--){
> System.out.println(stud[i].toString());
> }

Here you are looping through the array from 24 down to zero.
stud.length = 25 the size of your declared array NOT the number of valid
entries in that array. i or total would have the correct number of entries
I think from your previous code. If you did not have 25 folks come in, then
you will get a null ptr here, since stud[24] would be null.

Bob

Michael

ungelesen,
10.03.2006, 14:45:5110.03.06
an
Hi again,
I get the following;
java.lang.NullPointerException

at Sorts.findPosMin(Sorts.java:34)

at Sorts.selectionSort(Sorts.java:19)

at ReadTextFile.main(ReadTextFile.java:53)

Other error: null

It works just fine when I say the array size for student objects is 23. That
is when I do the following:

Student [] stud = new Student[23];

but when I put Student[] stud = new Student[25]; I get
nullPointerException.

I tried to even handle the exception by providing an empty catch clause but
no luck.

line 34: if (x[i].compareTo(x[posMinSoFar]) < 0)

line 19: posMin = findPosMin(x, fill);

line 53 : is Sorts.selectionSort(stud);

Thanks again.

cheers


"Michael" <mbia...@shaw.ca> wrote in message
news:YXjQf.133228$B94.51075@pd7tw3no...

Fred Kleinschmidt

ungelesen,
10.03.2006, 14:54:0010.03.06
an

"Michael" <mbia...@shaw.ca> wrote in message
news:YXjQf.133228$B94.51075@pd7tw3no...

You did not indicate where you get the exception, but I am assuming it is
here. I do not know what "Sorts.selectionSort()" is, but again I assume it
is doing something like:

for ( int i=0; i < stud.length; i++ ) {
/* do something here with stud[i] */
}

But you say you have not filled in all of the array; stud.length is 25, but
stud[23] is null.

You should either pass the actual number of items in the array to any
functiopn, or use something like a Vector instead of an array.

> for(i=stud.length-1;i>=0;i--){
> System.out.println(stud[i].toString());
> }
> System.out.println();
> System.out.println("The total number of students read = " + total);
> }
> catch(Exception e){
> System.out.println("Other error: " + e.getMessage());
> e.printStackTrace();
> }
> }
> }
>

--
Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Software Reuse Project


Roedy Green

ungelesen,
10.03.2006, 16:50:3910.03.06
an
On Fri, 10 Mar 2006 18:54:48 GMT, "Michael" <mbia...@shaw.ca> wrote,
quoted or indirectly quoted someone who said :

>Hello all, its been awhile. Anyways, I had a question regarding arrays. Say
>I want to create an array of 25objects, but I only end up filling the array
>with 23 objects. I know I need a counter to keep track of the objects read
>into the arrray. I have completed this but for some reason I am getting a
>NullPointerException; does it have anything to do with once an array is
>declared in size it can not be changed?

If you have an array of Objects that you won't totally fill, and if
you have only a vague idea of how many there will be, you can use an
ArrayList to keep track for you, and to autogrow the array. You pay
quite a speed penalty, for this convenience.

Obviously, an array is only partly full at some time in its career.
For that you must track the number of elements with your own variable.
If you have an array of Objects and go past that limit, you will pick
up a null reference since the JVM zero/nulls all arrays at allocation
time prior to other initialisation.

See http://mindprod.com/jgloss/gotchas.html#ARRAY

If you go out past the end of the array itself, you will get an
ArrayIndexOutOfBoundsException.
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Chris Smith

ungelesen,
12.03.2006, 18:04:0812.03.06
an
Michael <mbia...@shaw.ca> wrote:
> Hi again,
> I get the following;
> java.lang.NullPointerException
>
> at Sorts.findPosMin(Sorts.java:34)
>
> at Sorts.selectionSort(Sorts.java:19)
>
> at ReadTextFile.main(ReadTextFile.java:53)

Then Eric's guess was correct. The selection sort assumes that the
elements in the array are not null, so it is failing here. If you need
to use that specific sort method (why?), then you'll likely have to read
your file into one data structure, and then copy it into another to do
the sort. That's rather a pain, but it comes from the inflexible
interface of the sort method.

If it's okay to use Arrays.sort from the standard API, then you should
do so. It has an overloaded version that takes an array and two bounds
of the region to be sorted. In that case, you can do this:

Arrays.sort(stud, 0, total);

Or, as Eric said, use an ArrayList or other list data structure that
does this for you.

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

Michael

ungelesen,
13.03.2006, 22:48:1313.03.06
an
thanks guys, I have fixed the problem. I did this by just making a new array
and coping the elements over to the new array that contained the students.
"Roedy Green" <my_email_is_post...@munged.invalid> wrote in
message news:kar31212idvms6cv9...@4ax.com...
0 neue Nachrichten