this peice of code initialises X as a new formatter variable.
private Formatter X;
public void Create() {
try{
X = new Formatter("users.txt");
X.format("%1$20s %2$20s %3$20s %4$20s %5$20s %6$20s %7$20s %8$20s %9$20s \n","Firstname","Lastname","Password","ID","Addressln1","Addressln2","Addressln3","EstimatedValue","Tax Owed");
System.out.println("Due to there not being any users file present one has been created.");
}
catch(Exception e){
System.out.println("There is a users file present so i will not create another one.");
}
}
}
This is the piece of code i am having trouble with , at the X.format bit , it keeps giving me a null pointer error and i have tried everything to fix it.
public void WriteToFilecmd(){
Scanner input = new Scanner(System.in);
System.out.println("Please enter your First name");
String Fname = input.next();
System.out.println("Please enter your Last name");
String Lname = input.next();
System.out.println("Please enter your Password");
String Password = input.next();
System.out.println("Please enter your user ID");
String ID = input.next();
System.out.println("Please enter the first address line of your Property");
String addressln1 = input.next();
System.out.println("Please enter the second address line of your Property");
String addressln2 = input.next();
System.out.println("Please enter the third address line of your Property");
String addressln3 = input.next();
System.out.println("Please enter the properties estimated market value");
String EstimatedPropertyValue = input.next();
System.out.println("Please enter your tax owed");
String Taxowed = input.next();
input.close();
X.format("%1$20s %2$20s %3$20s %4$20s %5$20s %6$20s %7$20s %8$20s %9$20s \n",Fname,Lname,Password,ID,addressln1,addressln2,addressln3,EstimatedPropertyValue,Taxowed);
}
NullPointerExceptionon the linemeans either that
Xitself is null, or the method throws it. Normally, Java foundation classes handlenullarguments very well (andScanner#next()does not return null anyways) and don’t contain bugs, soXis most likelynullat the moment it’s being used.This could happen if your
createmethod catches an exception (see the console output), you overwriteXlater or if you don’t call thecreatemethod at all or you call it too late.Also note that pokemon exception handling (“gotta catch them all”,
catch(Exception e)) is a bad practice. Catch what you can handle, not what you can catch.