Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

File Writing Error

  Asked By: Kaua    Date: Dec 18    Category: Java    Views: 704
  

I'm having trouble with a file and I was hoping
someone could help me out.

It compiles fine but when I run it I come with the error:
Exception in thread "main" java.lang.NullPointerException
at RAF.<init>(RAF.java:18)
at RAF.main(RAF.java:33)

I need suggestions with the code please.
The code is as follows:

import java.io.*;
import java.awt.*;

public class RAF
{
private RandomAccessFile file;
private User[] users;

public RAF()
{

//open file
try {

file = new RandomAccessFile( "usernames.dat", "rw" );
for ( int i = 0; i < 100; i++ )
{
users[i] = new User();
System.out.println(users[i].getUsername()); //for error
checking purposes
file.writeChars(users[i].getUsername());
}

}

catch ( IOException ioException ) {
System.err.println( ioException.toString() );
System.exit( 1 );
}

}
public static void main(String[] args)
{
RAF s = new RAF();
}
}

class User
{
private String userName;
private String password;

public void User()
{
setUsername("");
setPassword("");

}
public void User(String nameStr, String pwStr)
{
setUsername(nameStr);
setPassword(pwStr);

}

public String getUsername()
{
return userName;
}
public String getPassword()
{
return password;
}

public void setUsername(String un)
{

//sets username
StringBuffer bufferun;

if ( un != null )
bufferun = new StringBuffer( un );
else
bufferun = new StringBuffer( 15 );
bufferun.setLength( 15 );

userName = bufferun.toString();
}


public void setPassword(String pw)
{
//sets password
StringBuffer bufferpw;

if ( pw != null )
bufferpw = new StringBuffer( pw );
else
bufferpw = new StringBuffer( 15 );
bufferpw.setLength( 15 );

password = bufferpw.toString();
}


}

Share: 

 

2 Answers Found

 
Answer #1    Answered By: Sean Grant     Answered On: Dec 18

you haven't initialised the array, try this:

private User[] users  = new User[100];

 
Answer #2    Answered By: Huette Miller     Answered On: Dec 18

I will try that out. I knew it had to be something
small.

 
Didn't find what you were looking for? Find more on File Writing Error Or get search suggestion and latest updates.




Tagged: