keep showing that:"java.lang.NullPointerException" - java

I want to read contents from a text file and then set it to some variables in car class. But it keeps showing me that "java.lang.NullPointerException". I don't know what's wrong with it. Could someone tell me what to do?
The error line is cars[0].setRegion(tokens[2]);
Here's the text file.
CarInLot KLM456 ND Meter4 120
CarInLot VMK123 ME Moving 0
CarInLotDKC003 WA Meter5 30
Meter1 None 10
CarInLot IML84U ND Meter6 800
Here's the test class.
import java.util.Scanner;
import java.io.*;
public class test
{
public static void main(String[] args) throws IOException
{
// Get the filename.
String filename = "input.txt";
// Open the file.
File file = new File(filename);
Scanner inputFile = new Scanner(file);
Car[] cars = new Car[4];
while (inputFile.hasNext())
{
String filecotent = inputFile.nextLine();
String[] tokens = filecotent.split(" ");
if(filecotent.startsWith("CarInLot")){
cars[0].setRegion(tokens[2]);
cars[0].setMinutes(Integer.parseInt(tokens[4]));
}
if(filecotent.startsWith("Meter")){
cars[0].setPlate(tokens[1]);
}
}
System.out.println(cars[0].toString());
// Close the file.
inputFile.close();
}
}
Here's car class.
public class Car {
private String plate;
private String region;
private int minutes;
public Car(String carPlate, String carRegion,
int carMinutes) {
plate = carPlate;
region = carRegion;
minutes = carMinutes;
}
public Car(Car object2) {
plate = object2.plate;
region = object2.region;
minutes = object2.minutes;
}
public void setPlate(String pl) {
plate = pl;
}
public void setRegion(String re) {
region = re;
}
public void setMinutes(int mi) {
minutes = mi;
}
public String getPlate() {
return plate;
}
public String getRegion() {
return region;
}
public int getMinutes() {
return minutes;
}
public String toString() {
String string = "Car's information: "
+ "\n"
+ "\nLicense Plate: " + plate
+ "\nLicense Plate Resgistration Region: " + region
+ "\nParked time" + minutes
+ "\n";
return string;
}
}

So you've got this code
Car[] cars = new Car[4];
while (inputFile.hasNext())
{
String filecotent = inputFile.nextLine();
String[] tokens = filecotent.split(" ");
if(filecotent.startsWith("CarInLot")){
cars[0].setRegion(tokens[2]);
cars[0].setMinutes(Integer.parseInt(tokens[4]));
}
...
cars is initialized, but the elements inside it aren't. You need to initialize those first, otherwise they are null and you get NullPointerException.
cars[someIndex] = new Car(...);
Also, the way you have your code now, you'll always be overwriting the same Car reference in the array, ie. the one at index 0. You may want to use an incrementing index to initialize each element.

Related

I am not correctly reading from the text file into an ArrayList after parsing each line into an object

I am trying to read from the txt file and then parse through it and make each line a new object in an ArrayList. I keeps telling me its null and I cannot figure out why. I have not used java in a long time so I'm sure its dumb.
public class AccessibilityTest {
private String cat;
private String googErr;
private String waveErr;
private String sortErr;
private String lintErr;
private String desc;
public AccessibilityTest(String cat,String googErr,String waveErr,String sortErr,String lintErr, String desc){
this.cat = cat;
this.googErr = googErr;
this.waveErr = waveErr;
this.sortErr = sortErr;
this.lintErr = lintErr;
this.desc = desc;
}
public static void main(String[] args) {
AccessibilityResults.readTxtFile("a11yCheckersResults.txt");//this is one place im getting the error and its me trying to target that txt file
System.out.println();
}
public String getCategory() {
return cat;
}
public String getGoogleResult() {
return googErr;
}
public String getWaveResult() {
return waveErr;
}
public String getSortsiteResult() {
return sortErr;
}
public String getAslintResult() {
return lintErr;
}
public String getDescription() {
return desc;
}
#Override
public String toString(){
return "fsdfse"+ getCategory() + getGoogleResult()+ getWaveResult()+ getSortsiteResult() + getAslintResult() + getDescription();
}
}
This is the other file where I am actually parsing through the txt file and creating the objects.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class AccessibilityResults {
private static ArrayList<AccessibilityTest> list;
public AccessibilityResults() {
list = new ArrayList<>();
}
public static void readTxtFile(String fileName){
try(Scanner reader = new Scanner(new File(fileName))){
while(reader.hasNextLine()){
String cat = reader.next();
String err1 = reader.next();
String err2 = reader.next();
String err3 = reader.next();
String err4 = reader.next();
String desc = reader.nextLine();
list.add(new AccessibilityTest(cat, err1, err2, err3, err4,desc));//this is one spot im getting the error
}
} catch(FileNotFoundException e){
System.out.println("File not found: " + fileName);
}`enter code here`
}
}
//txt file
//a11yCheckersResults.txt
The reason is that list and readTxtFile is static method,but the readTxtFile() that init list is not static,and in java static properties and method will be inited before none static which cause it
To solve it,there are several options:
one option is just to remove all the static in list and readTxtFile(),another options is just init list when declare it private static ArrayList<AccessibilityTest> list = new ArrayList<>();
// static
private static ArrayList<AccessibilityTest> list;
// no static,so list will always be null
public AccessibilityResults() {
list = new ArrayList<>();
}
// static
public static void readTxtFile(String fileName){
try(Scanner reader = new Scanner(new File(fileName))){
while(reader.hasNextLine()){
String cat = reader.next();
String err1 = reader.next();
String err2 = reader.next();
String err3 = reader.next();
String err4 = reader.next();
String desc = reader.nextLine();
list.add(new AccessibilityTest(cat, err1, err2, err3, err4,desc));//this is one spot im getting the error
}
} catch(FileNotFoundException e){
System.out.println("File not found: " + fileName);
}
}
}

How to get user input and store in custom object? JAVA

Henlo,
Basically what im trying to do is get user inputs and store in a custom object but I have no idea on how to go about it. I have created a loadDataFromConfig() method? that works fine when creating the object SmartHome app = new SmartHome(loadDataFromConfig());.
But I am completely stumped on how to get user inputs and store them in this format: dev[0] = new SmartDevice("device 1",1.3,true);.
All the code that is meant to run should be inside the main method in Step1.java
Here are the 3 classes used for the code (ignore comments they are just notes for me):
package SmartHomeApp;
public class SmartDevice {
private String name;
private double location;
private boolean switchedOn;
public SmartDevice(String val1, double val2, boolean val3) {
setName(val1);
setLocation(val2);
setSwitchedOn(val3);
}
//YOU CANT ACCESS the 'private classes' so you need to GET them
public void setName(String value) {name = value;}
public void setLocation(double value) {location = value;}
public void setSwitchedOn(boolean value) {switchedOn = value;}
public String getName() {return name;}
public double getLocation() {return location;}
public boolean getSwitchedOn() {return switchedOn;}
}
package SmartHomeApp;
public class SmartHome
{
private SmartDevice[] smrtDev;
public SmartHome(int size) {
smrtDev = new SmartDevice[size];
}
public SmartHome(SmartDevice[] values) {
smrtDev = values;
}
public int size() {return smrtDev.length;}
// can't do toString() for some reason??
public void ToString() {
for(int i=0; i<size();i++)
{
if(smrtDev[i] != null ){
System.out.println("----------");
System.out.println("-DEVICE "+(i+1)+"-");
System.out.println("----------");
System.out.println("Name: "+smrtDev[i].getName());
System.out.println("Location: "+smrtDev[i].getLocation());
System.out.println("Switched On: "+smrtDev[i].getSwitchedOn());
}
}
}
}
package SmartHomeApp;
import java.util.*;
public class Step1 {
public static void main(String args[]) {
SmartHome app = new SmartHome(loadDataFromConfig());
app.ToString();
}
public static SmartDevice[] loadDataFromConfig()
{
SmartDevice[] dev = new SmartDevice[20];
dev[0] = new SmartDevice("device 1",1.3,true);
dev[1] = new SmartDevice("device 2",2.3,false);
dev[2] = new SmartDevice("device 3",3.3,true);
dev[4] = new SmartDevice("device 5",4.3,false);
dev[19] = new SmartDevice("device 20",5.3,false);
return dev;
}
}
Some of the improvements required in your code are as follows:
Follow Java naming conventions e.g. ToString() should be toString(). Check this to learn more about toString(). Most of the IDEs (e.g. eclipse) provide a feature to generate toString() method on click of a button. Whatever way (either manual or with the help of your IDE) you generate it, it must return a String.
You should do away with using next(), nextInt(), nextDouble() etc. and use nextLine() instead. Check this to learn more it. To give you an idea what problems next(), nextDouble() can cause, try entering a name with a space e.g.
Enter size:
2
Name:
Light Amplification by Stimulated Emission of Radiation
Location:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at Main.main(Main.java:83)
Given below is a sample code incorporating the improvements mentioned above:
import java.util.Scanner;
class SmartDevice {
private String name;
private double location;
private boolean switchedOn;
public SmartDevice(String val1, double val2, boolean val3) {
setName(val1);
setLocation(val2);
setSwitchedOn(val3);
}
// YOU CANT ACCESS the 'private classes' so you need to GET them
public void setName(String value) {
name = value;
}
public void setLocation(double value) {
location = value;
}
public void setSwitchedOn(boolean value) {
switchedOn = value;
}
public String getName() {
return name;
}
public double getLocation() {
return location;
}
public boolean getSwitchedOn() {
return switchedOn;
}
#Override
public String toString() {
return "SmartDevice [name=" + name + ", location=" + location + ", switchedOn=" + switchedOn + "]";
}
}
class SmartHome {
private SmartDevice[] smrtDev;
public SmartHome(int size) {
smrtDev = new SmartDevice[size];
}
public SmartHome(SmartDevice[] values) {
smrtDev = values;
}
public int size() {
return smrtDev.length;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (SmartDevice smartDevice : smrtDev) {
sb.append(smartDevice.toString()).append("\n");
}
return sb.toString();
}
}
public class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
int size = getPositiveInt(myObj, "Enter size: ");
SmartDevice[] newList = new SmartDevice[size];
for (int i = 0; i < newList.length; i++) {
System.out.print("Name: ");
String x = myObj.nextLine();
double y = getFloatingPointNumber(myObj, "Location: ");
boolean z = getBoolean(myObj, "Is on?: ");
newList[i] = new SmartDevice(x, y, z);
}
SmartHome newDevice = new SmartHome(newList);
System.out.println(newDevice);
}
static int getPositiveInt(Scanner in, String message) {
boolean valid;
int n = 0;
do {
valid = true;
System.out.print(message);
try {
n = Integer.parseInt(in.nextLine());
if (n <= 0) {
throw new IllegalArgumentException();
}
} catch (IllegalArgumentException e) {
System.out.println("This in not a positive integer. Please try again.");
valid = false;
}
} while (!valid);
return n;
}
static double getFloatingPointNumber(Scanner in, String message) {
boolean valid;
double n = 0;
do {
valid = true;
System.out.print(message);
try {
n = Double.parseDouble(in.nextLine());
} catch (NumberFormatException | NullPointerException e) {
System.out.println("This in not a number. Please try again.");
valid = false;
}
} while (!valid);
return n;
}
static boolean getBoolean(Scanner in, String message) {
System.out.print(message);
return Boolean.parseBoolean(in.nextLine());
}
}
A sample run:
Enter size: x
This in not a positive integer. Please try again.
Enter size: -2
This in not a positive integer. Please try again.
Enter size: 10.5
This in not a positive integer. Please try again.
Enter size: 2
Name: Light Amplification by Stimulated Emission of Radiation
Location: 123.456
Is on?: true
Name: Vacuum Diode
Location: 234.567
Is on?: no
SmartDevice [name=Light Amplification by Stimulated Emission of Radiation, location=123.456, switchedOn=true]
SmartDevice [name=Vacuum Diode, location=234.567, switchedOn=false]
So as suggested I tried to do the following:
public static void main(String args[]) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter size: ");
int size = myObj.nextInt();
SmartDevice[] newList = new SmartDevice[size];
for(int i =0; i<newList.length;i++) {
System.out.println("Name: ");
String x = myObj.next();
System.out.println("Location: ");
double y = myObj.nextDouble();
System.out.println("Is on?: ");
boolean z = myObj.nextBoolean();
newList[i] = new SmartDevice(x,y,z);
}
SmartHome newDevice = new SmartHome(newList);
newDevice.ToString();
}
Got it working but not sure if this is the most efficient way to do so??

Read data from a .txt file and create an object array

I need some help please: I'm making a flight roster simulation in java. The roster will hold 25 passengers, 22 of which come from a text file (PassengerList.txt). For each passenger there are 3 required data points; name, seat class & seat # and 2 optional data points frequent flyer number & frequent flyer points. Each passenger is on its own line and each data point is separated by a comma. For example:
Allen George,Economy Class,8A,#GEO456,10000
Judy Hellman,Economy Class,8B
I have this class, along with constructor so far:
public class Passengers
{
private String name, type, seat, flyernum;
private int points;
//Constructor to intialize the instance data
Passengers(String full_name, String seat_type, String seat_number,
String frequent_flyer_number, int frequent_flyer_points)
{
name=full_name;
type=seat_type;
seat=seat_number;
flyernum=frequent_flyer_number;
points=frequent_flyer_points;
} //end Passengers
What I need to do is to read each line from the text file and create the array, i.e. make the first look line look something like this:
Passenger passenger1 = new Passenger ("Allen George","Economy Class","8A"
,"#GEO456",10000)
Into an array like this:
Passenger[0] = passenger1;
I am obviously a java beginner, but I have been caught up on this for so long and I keep getting different error message after error message when I try something new. I have been using Scanner to read the file. The text file does not need to be overwritten, just read and scanned by the program. Only Arrays can be used as well, ArrayList is a no go. Only two files too, the Passengers class and the main method. Please help! Thank you!
You can do it as bellow :
First you need a Passenger.class. It would look something like this (Note that I have added a toString():
public class Passenger {
private String name, type, seat, flyernum;
private int points;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSeat() {
return seat;
}
public void setSeat(String seat) {
this.seat = seat;
}
public void setFlyernum(String flyernum) {
this.flyernum = flyernum;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
#Override
public String toString() {
return "Passenger{" +
"name='" + name + '\'' +
", type='" + type + '\'' +
", seat='" + seat + '\'' +
", flyernum='" + flyernum + '\'' +
", points=" + points +
'}';
}
}
Now for getting the passenger details from the file, I have create GetPassengerDetails.class, it handles reading in the data from the CSV file and allocating the right values for each Passenger.
public class GetPassengerDetails{
/** Reads the file one line at a time. Each line will is that split up and translated into a Passenger object */
public List<Passenger> getPassengersFromFile(BufferedReader reader) throws IOException {
List<Passenger> passengers = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
String[] passengerDetails = line.trim().split(",");
Passenger passenger = new Passenger();
for (int i = 0; i < passengerDetails.length; i++) {
SetPassengerName(passengerDetails, passenger, i);
setPassengerFlightType(passengerDetails, passenger, i);
setPassengerSeatNumber(passengerDetails, passenger, i);
SetPassengerFlyerNumber(passengerDetails, passenger, i);
setPassengerPoints(passengerDetails, passenger, i);
}
passengers.add(passenger);
}
return passengers;
}
private void setPassengerPoints(String[] passengerDetails, Passenger passenger, int i) {
if(i< passengerDetails.length && i == 4) {
passenger.setPoints(Integer.parseInt(String.valueOf(passengerDetails[4])));
}
}
private void SetPassengerFlyerNumber(String[] passengerDetails, Passenger passenger, int i) {
if(i< passengerDetails.length && i == 3) {
passenger.setFlyernum(String.valueOf(passengerDetails[3]));
}
}
private void setPassengerSeatNumber(String[] passengerDetails, Passenger passenger, int i) {
if(i< passengerDetails.length && i == 2) {
passenger.setSeat(String.valueOf(passengerDetails[2]));
}
}
private void setPassengerFlightType(String[] passengerDetails, Passenger passenger, int i) {
if(i< passengerDetails.length && i == 1) {
passenger.setType(String.valueOf(passengerDetails[1]));
}
}
private void SetPassengerName(String[] passengerDetails, Passenger passenger, int i) {
if(i< passengerDetails.length & i == 0) {
passenger.setName(String.valueOf(passengerDetails[i]));
}
}
}
Here is the main method to test the above code :
public class Main {
public static void main(String[] args) throws IOException {
String fileName = "resources/passengers.csv";
BufferedReader reader = new BufferedReader(new FileReader(fileName));
GetPassengerDetails passengerDetails = new GetPassengerDetails();
List<Passenger> passengers = passengerDetails.getPassengersFromFile(reader);
// For Testing Purposes lets get the Passengers
for (Passenger passenger : passengers
) {
System.out.println(passenger.toString());
}
}
}
After running the main method, this is the result that you will get :
Use this main method to read data from text files and converge data into the Passengers object. The whole list of passengers in passengersList objec.
public static void main(String[] args) {
List<Passengers> passengersList = new ArrayList<Passengers>();
File file = new File("Your file location..");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null){
String[] data = st.split(",");
String flyNumber = null;
int flyPoints = 0;
switch (data.length){
case 4: flyNumber = data[3];
break;
case 5: flyNumber = data[3];
flyPoints = Integer.valueOf(data[4]);
break;
}
Passengers passenger = new Passengers(data[0], data[1], data[2], flyNumber, flyPoints);
passengersList.add(passenger);
}
System.out.println(passengersList.get(0));
} catch (IOException e) {
e.printStackTrace();
}
}

printf statement working for one instance of the same class but not another

this is my first time posting so hopefully all goes well. I am having a problem with the following program.
public class Project3 {
public static String fName = "drum_members.txt";
private static Scanner fin;
private static PrintWriter fout;
private static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
String membershipLength;
Member m_1 = new Member();
Member m_2 = new Member();
Member m_3 = new Member();
Member m_4 = new Member();
try {
fin = new Scanner(new File(fName));
} catch (FileNotFoundException e) {
System.err.println("Error opening the file " + fName);
System.exit(1);
}// end try
m_1.Member();
m_1.calculateFreeItems();
m_1.printMember();
m_2.Member();
m_2.calculateFreeItems();
m_2.printMember();
m_3.Member();
m_3.calculateFreeItems();
m_3.printMember();
m_4.Member();
m_4.calculateFreeItems();
m_4.printMember();
}
public static class Member{
public int id;
public String name;
public String nickName;
public int monthsMembership;
public String favoriteItem;
public int freeItems;
public void Member()
{
name = fin.next();
nickName = fin.next();
monthsMembership = fin.nextInt();
favoriteItem = fin.next();
fin.nextLine();
}
private int calculateFreeItems()
{
freeItems = monthsMembership/12 +1;
return (freeItems);
}
public void setFavoriteitem()
{
System.out.print("Enter new favorite item: ");
favoriteItem = keyboard.next();
}
private String calculatemembershipLength()
{
if(monthsMembership < 12)
return (monthsMembership + "months,");
else
return (monthsMembership/12 + " years, " + monthsMembership%12 + " months,");
}
public void printMember()
{
String months = this.calculatemembershipLength();
System.out.printf("Member #1 - NAME: %22s, NICKNAME:%22s, MEMBER SINCE: %22s FAVORITE ITEM:%22s, FREE ITEMS PER MONTH: %d\n",
name, nickName, months, favoriteItem, freeItems);
}
}
}
After debugging all I know is that the printf statement doesn't work the THIRD time, it will work the 4th time no problem. Any help would be greatly appreciated, and thanks for your time.

Cannot figure out why the array displays null

I want to read a txt file and store each record in the file to an array of objects called data[]. Everything works except the record parts are not being assigned correctly in the data[].
This is the format for the record.txt...
4252 4 item1
2435 23 item2
4355 16 item3
so on and so on...
I want to keep using the methods I have been using even if there is an easier way (there always is).
Thank you much ...
import java.util.Scanner;
import java.io.*;
public class SortsTest
{
private static Data[] data;
private static String file_to_read;
private static int num_of_records,
current_record = 0;
private final static int RECORD_DATA = 3;
private static Scanner scan_file1;
public static void main(String[] args) throws IOException
{
try {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a file name: ");
file_to_read = scan.next();
System.out.print("\nInput file = " + file_to_read);
System.out.print("\n# of records = ");
num_of_records = scan.nextInt();
scan_file1 = new Scanner(new File(file_to_read));
//---------------------- populate data array ------------------------
while (scan_file1.hasNext())
{
data = new Data[num_of_records];
String record[] = new String[RECORD_DATA];
for(int i = 0; i < RECORD_DATA; i++)
{
String line = scan_file1.next();
record[i] = line;
}
data[current_record] = new Data(record[0],record[1], record[2]);
current_record++;
}
//--------------------------------------------------------------------
//System.out.print("\n\nRecord 10: " + data[10].getPartName() + " " + data[10].getQuantity() + " " + data[10].getPartNumber());
System.out.print("\n\nRecord 10: " + data[10]);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
///////////////////////////// Data file /////////////////////////////////
import java.util.Scanner;
import java.io.*;
public class Data
{
private int part_num,
quantity;
private String part_name;
private Scanner scan_file1;
public Data(String part, String quan, String name)
{
part_num = Integer.parseInt(part);
quantity = Integer.parseInt(quan);
part_name = name;
}
public void setPartNumber(int num)
{
part_num = num;
}
public void setQuantity(int quan)
{
quantity = quan;
}
public void setPartName(String name)
{
part_name = name;
}
public int getPartNumber()
{
return part_num;
}
public int getQuantity()
{
return quantity;
}
public String getPartName()
{
return part_name;
}
}
You create a new empty data array every iteration through the while loop, try this:
data = new Data[num_of_records];
while (scan_file1.hasNext())
{
without going too deep into your code, I suspect this is part of your issue:
//---------------------- populate data array ------------------------
while (scan_file1.hasNext())
{
// you recreate your array every loop iteration
data = new Data[num_of_records];
instead, you need to do the following:
//---------------------- populate data array ------------------------
data = new Data[num_of_records];
while (scan_file1.hasNext())
{

Categories

Resources