need help inputting values into an array
hi im trying to input values from a txt file gn.txt into an array guestNumber
this is my code so far
Code :
Scanner cc = new Scanner( new File("CC.txt") );
Scanner sn = new Scanner( new File("sn.txt") );
Scanner ng = new Scanner( new File("gn.txt") );
String line ;
String line2 ;
String line3 ;
System.out.println("course code"+" " + "Student Number" +" "+"Number of guests");
int lineCount = 0;
BufferedReader br2 = new BufferedReader(new FileReader("gn.txt"));
while ((line = br2.readLine()) != null) {
lineCount++;
}
System.out.println(lineCount);
double guestNumbers[] = new double[lineCount];
for(int c=0; c< lineCount; c++)
{
double e=Double.parseDouble(br2.readLine());
System.out.println(e);
guestNumbers[c]= e;
}
while( cc.hasNext() && sn.hasNext() && ng.hasNext() ){
line = cc.nextLine();
line2 = sn.nextLine();
line3 = ng.nextLine();
int i=Integer.parseInt(line);
int i2=Integer.parseInt(line2);
double i3=Double.parseDouble(line3);
System.out.println(i + " " + i2 + " " + i3);
}
System.out.println(guestNumbers[0]);
System.out.println(guestNumbers[1]);
System.out.println(guestNumbers[2]);
System.out.println(guestNumbers[3]);
cc.close();
sn.close();
ng.close();
when i run the program im getting a null pointer exception
Re: need help inputting values into an array
while ((line = br2.readLine()) != null)
Normally in while and if statements, use two "=" in a row for equals.
Re: need help inputting values into an array
Wait...I see a potential Null Pointer Exception!
You never initialize the String variable line nor do you change it to anything.
Try changing it to
while ((br2.readLine()) != null) {
lineCount++;
I know that a Null Pointer Exception is occurring because line was never initialized.
Hence
while ((line = br2.readLine()) != null) {
lineCount++;
will tell it...maybe since you have only 1 "="...to stop the while loop if line is equal to null.
Well, it's never been initialized so it is null.
Ok...that itself might not be a Null Pointer Exception.
However, as it is, lineCount is now still 0.
Therefore your array is empty and you're printing null values at the end.
Re: need help inputting values into an array
One last time Javapenguin...did you even try that piece of code you are trying to advise someone else on? Continuing to hand out unsolicited, untested advice eh?
pds8475, it helps to see the full stack trace...this contains important information. To define the problem...BufferedReader.readLine returns null when the end of stream is reached. You read until this point, then try to read another line below, thus the reader returns null. To get around not knowing how many lines there are in the file, use an ArrayList so you can collect all the lines without the need to count the lines then read the file