Getting nullpointerexception while using constructor - java

public class Author {
private int id;
private String name;
private String university;
private String department;
private String email;
private int article1;
private int article2;
private int article3;
private int article4;
private int article5;
//constructors and getter/setters are generated automatically, not adding to have space
}
This is my Author class. This class only has these attributes. Also I have a readDaFile class which is created to read author.txt and and create author objects.
import java.util.Scanner;
import java.io.*;
public class readAuthor {
private Scanner reader;
private String temp;
private String[] split;
public Author[] authorList;
private int dummyInt,dummyArticle1=0 ,dummyArticle2=0 ,dummyArticle3=0,dummyArticle4,dummyArticle5;
private int i=0;
private String name , university , department , email ;
public void tryOpeningOrDieTrying(){
try{
reader = new Scanner(new File("Author.txt"));
}
catch(Exception exo){
System.out.println("Can not find file.");
}
}
public void readDaFile(){
while(reader.hasNext()){
temp = reader.nextLine();
split = temp.split(" ");
name = "NOTGIVEN";
university = "NOTGIVEN";
department = "NOTGIVEN";
email = "NOTGIVEN";
dummyInt = 0;
dummyArticle1 = 0;
dummyArticle2 = 0;
dummyArticle3 = 0;
dummyArticle4 = 0;
dummyArticle5 = 0;
dummyInt = Integer.parseInt(split[1]);
if(split.length>2){ name = split[2]; }
if(split.length>3){ university = split[3]; }
if(split.length>4){ department = split[4]; }
if(split.length>5){ email = split[5]; }
if(split.length>6){ dummyArticle1 = Integer.parseInt(split[6]); }
if(split.length>7){ dummyArticle2 = Integer.parseInt(split[7]); }
if(split.length>8){ dummyArticle3 = Integer.parseInt(split[8]); }
if(split.length>9){ dummyArticle4 = Integer.parseInt(split[9]); }
if(split.length>10){ dummyArticle5 = Integer.parseInt(split[10]); }
System.out.println(dummyInt+name+university+department+email+dummyArticle1+dummyArticle2+dummyArticle3+dummyArticle4+dummyArticle5);
//authorList[i] = new Author(dummyInt,name,university,department,email,dummyArticle1,dummyArticle2,dummyArticle3,dummyArticle4,dummyArticle5);
i++;
//System.out.println(split[1]);
//System.out.println(split.length);
}
}
public void sealDaGates(){
reader.close();
}
}
Simply I'm reading lines first then split them into sub-elements to create author objects. But Author.txt might not give all author attributes.
For example :
AUTHOR 100
AUTHOR 101 Ruonan_Li MIT Computer_Science ruonan#mit.edu 1002001 1002009 1002004
To prevent sending null parameters to author constructor,I am initializing every attribute variable for every loop. I also checked initialized attribute variables by printf-ing them. They seem to work as intended. If I can't successfully read an attribute from txt , program sends NOTGIVEN or 0 to constructor. But still I am having nullpointerexception at line :
authorList[i] = new Author(dummyInt,name,university,department,email,dummyArticle1,dummyArticle2,dummyArticle3,dummyArticle4,dummyArticle5);
Thanks in advance

You're never initializing authorList, so that's null. It's not the constructor call which is failing - it's the assignment into the array. You need:
authorList = new Author[...];
somewhere. Alternatively - and almost certainly preferrably - use a List<Author>, e.g.
private final List<Author> authorList = new ArrayList<Author>();

Looks like you forgot to initialize the authorList array. In the constructor, add this line authorList = new Author[100]; and that should fix it. Change 100 to whatever number of elements you desire.

Related

Reading from an file with comma as delimiter and storing the data into an object and then saving the data into list [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 11 months ago.
import java.util.*;
public class ReadFile {
public static class Em implements Comparable<Em> {
private int id;
private String name;
private double Salary;
public int getId() {
return id;
}
// same get methods for sal and name here
public Em(int id, String name, double e) {
this.id = id;
this.name = name;
this.sal = sal;
}
}
public static void main(String a[]) throws IOException {
String record;
List<Em> eL = new ArrayList<Em>();
BufferedReader be = new BufferedReader(new File("Location"));
List<String> arrList = new ArrayList<>();
try {
while ((record = br.readLine()) != null) {
String[] rows = record.spilt(",");
Em e = null;
int a = Integer.parseInt(rows[0]);
String b = rows[1];
double c = Double.parseDouble(rows[2]);
eL.add(new Em(a, b, c);
arlist.add(Arrays.toString(rows));
System.out.println(eL.toString);
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
Please Note:
Location of file is correct.
Any typo might be there.
The file contains data as follows:
1,Duke,13000
2,Jake,14000
...
OUTPUT:
[test.ReadFile$Em#7852e922]
[test.ReadFile$Em#7852e922,test.ReadFile$Em#4e25154f]
I need help
Am I doing it correctly
Any alternate program will help
Future:
I have to write emp details who has maximum salary into another file
Try overriding toString() method in Em class.
#Override
public String toString() {
return this.id + " " + this.name + " " + this.salary;
}
Your approach is good (if we forget the typos which, I assume, are not present in your code). The reason your program is outputting [test.ReadFile$Em#7852e922] [test.ReadFile$Em#7852e922,test.ReadFile$Em#4e25154f] is because of the way you are trying to print it. What you see is the memory adress of your ArrayList, not the content. To print the content of your ArrayList, you need to use a for loop that goes through the entire content of your ArrayList index by index and then prints its content. Here's a quick example:
for (int i = 0; i < eL.length(); i++) {
System.out.println(eL.get(i).getA)
System.out.println(eL.get(i).getB)
System.out.println(eL.get(i).getC)
}
This way of doing it gets the Em object for every index in the El ArrayList, and then prints its A, B and C value using a get command that you can easily add to your Em Class.

How to load records into a jTable from a file?

I'm making a GUI program, using netbeans, that is supposed to be an interface for managing records in a video store.
This is the interface. It's two tabs, and one side allows a person to add records, whilst the other tab displays them. When a person adds records, they are added to a .dat file named output. I would like to use the .dat file as a permanent storage area for the video records, and basically what I want to happen is that when one loads the GUI class, the program loads all the records from the .dat file. I have already created my code, but I'm getting the following error:
run:
java.io.EOFException
at java.io.RandomAccessFile.readChar(RandomAccessFile.java:773)
at videostore.BinaryFile.getString(BinaryFile.java:82)
at videostore.BinaryFile.load(BinaryFile.java:116)
at videostore.VideoStore.main(VideoStore.java:409)
Exception in thread "main" java.lang.NullPointerException
at videostore.VideoStore.main(VideoStore.java:420)
/Users/(my Name)/Library/Caches/NetBeans/8.1/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 2 seconds)
And then I'll paste all relevant code below.
In the main method of the GUI class, named VideoStore.java:
file = new BinaryFile("/Users/hanaezz/Desktop/output.dat");
int length = file.length();
int ID = 1;
for (int xx = 0; xx < length; xx += file.getRecordLength()) {
Video load = file.load(xx);
String tempName = load.getVideoName();
String tempProd = load.getProducer();
String tempRat = load.getRating();
String tempGenre = load.getGenre();
short tempNum = load.getVidNum();
float tempPrice = load.getvideoPrice();
Object[] row = {ID, tempName, tempProd, tempGenre, tempRat, tempNum, tempPrice};
model.addRow(row);
ID++;
}
in the VideoStore constructor class:
public VideoStore() {
initComponents();
model = (DefaultTableModel) displayVideos.getModel();
}
And within the BinaryFile class:
private static final int RecordLength = 112;
public static Video load(int place){
String name = "", prod="", rat="", genre="";
float price = 1;
short number = 1;
try {
raf.seek(place);
name = getString(20);
prod = getString(15);
rat = getString(20);
genre = getString(10);
price = Float.parseFloat(getString(4));
number = Short.parseShort(getString(4));
writeString(20, name);
writeString(15, prod);
writeString(10, genre);
writeString(4, VideoStore.vPrice.getText());
writeString(4, VideoStore.vNumber.getText());
writeString(4, rat);
} catch (Exception e) {
e.printStackTrace();
}
Video r = new Video(name, prod, genre, rat, number, price);
return r;
}
public static int getRecordLength() throws IOException{
return RecordLength;
}
public static int length() throws IOException {
return (int)raf.length();
}
And finally, my Video class:
private static String videoName;
private static String producer;
private static String rating;
private static String genre;
private static short videoNumber;
private static float videoPrice;
public Video(String a, String b, String c, String d, short e, float f){
videoName = a;
producer = b;
rating = c;
genre = d;
videoNumber = e;
videoPrice = f;
}
...Then mutator and accessor methods for each variable in the class...
#Override
public String toString(){
return videoName + "\t" + producer +
"\t" + rating + "\t" + genre +
"\t" + videoNumber + "\t" + videoPrice;
}
So yeah, my issue is that I can't figure out how to load records from the file into the table. In my code I tried to use a loop that would iterate through each record in the file based on the record's size.. however it doesn't seem to have worked. If anyone would like to see my full code or needs more information, don't hesitate to contact me :)
First, you should use a more Object Oriented approach.
Your video class contains nothing but static attributes, when it should looks like this:
public class Video implements Serializable{
private String name;
private String producer; //consider using an object for this
private String rating; //consider using a numeric type for this
private String genre; //consider using an object for this
private int number;
private double price;
//getters and setters
}
Check the Object-Oriented Programming Concepts.
To add a new video, you get the user input from the graphic interface, and use it to create a Video object.
Video video = new Video();
video.setName(nameTextField.getText());
//same for the other attributes
Then you can keep all your videos in a List.
List<Video> videosList = new ArrayList<>();
videoList.add(video);
Then you can serialize your list to a file.
try(FileOutputStream outputFile = new FileOutputStream("/path/to/file");
ObjectOutputStream out = new ObjectOutputStream(outputFile)){
out.writeObject(videoList);
} catch (IOException e1) {
// Handle the exception
}
To read back your list from the file, you need to deserialize it:
try(FileInputStream inputFile = new FileInputStream("/path/to/file");
ObjectInputStream in = new ObjectInputStream(inputFile)){
videoList = (List<Video>)in.readObject();
} catch (IOException e1) {
// Handle the exception
}

Read data from a text file and create an object

I need some help:
I'm making a Supermarket simulation on Java, but I've got one problem, I have a text file (Stock.txt) where I have all the supermarket stock on it for example:
0-Bakery-Chocolate Cake-$12.5-250
1-Meat-Premium Steak-$2.6-120
2-Seafood-Tuna - $1.2-14
...
Where the first number is the "id" for the product, next is the department the product belongs, third is the name of the product, the next thing is the price, and the last number is how much pieces of the product the stock has.
I have this class:
public class Product {
protected String name;
protected double price;
protected String department;
protected int id;
protected int stock;
}
So, basically what I need to do is to read each line from the text file and create the product, i.e. for the first line make something like this:
Product product1 = new Product(0,"Bakery","Chocolate Cake", 12.5, 250);
And then add it to an array
Product[0] = product1;
For all the things that are in the text file, then, when running the simulation each costumer will buy a random quantity of random products in stock, so the stock number will decrease. Finally, when the simulation ends, the program must write in the same text file, the modify quantity of each product.
The thing is that maybe it's too easy to do but I have no idea of how to do this, because reading and writing a file in Java has been a real problem for me since I started programming in Java (I'm a beginner).
I have some ideas of using the BufferedReader and the StringTokenizer classes for the reading and creating the object problems, but I can't figure it out how to do it, and I have no idea of how must I do the overwritting problem.
I'd really appreciate your help!
Oh! By the way, I really need to use only the arrays, so using an ArrayList or any other structure it's not even a choice :(
This is a good job for a Scanner to read in the data. As far as not being able to use collections like ArrayList you'll have to dynamically reallocate an array yourself.
Try the following:
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("Stock.txt"));
input.useDelimiter("-|\n");
Product[] products = new Product[0];
while(input.hasNext()) {
int id = input.nextInt();
String department = input.next();
String name = input.next();
double price = Double.valueOf(input.next().substring(1));
int stock = input.nextInt();
Product newProduct = new Product(name, price, department, id, stock);
products = addProduct(products, newProduct);
}
for (Product product : products) {
System.out.println(product);
}
}
private static Product[] addProduct(Product[] products, Product productToAdd) {
Product[] newProducts = new Product[products.length + 1];
System.arraycopy(products, 0, newProducts, 0, products.length);
newProducts[newProducts.length - 1] = productToAdd;
return newProducts;
}
public static class Product {
protected String name;
protected double price;
protected String department;
protected int id;
protected int stock;
private static NumberFormat formatter = new DecimalFormat("#0.00");
public Product(String n, double p, String d, int i, int s) {
name = n;
price = p;
department = d;
id = i;
stock = s;
}
#Override
public String toString() {
return String.format("ID: %d\r\nDepartment: %s\r\nName: %s\r\nPrice: %s\r\nStock: %d\r\n",
id, department, name, formatter.format(price), stock);
}
}
Results:
ID: 0
Department: Bakery
Name: Chocolate Cake
Price: 12.50
Stock: 250
ID: 1
Department: Meat
Name: Premium Steak
Price: 2.60
Stock: 120
ID: 2
Department: Seafood
Name: Tuna
Price: 1.20
Stock: 14
For simplicity, I have defined all the items as String.
Product DAO:
public class Product {
private String name;
private String price;
private String department;
private String id;
private String stock;
//generate `enter code here`
//getters & setters
//toString
Put your product list in "testData/product.txt". This is assuming that your list of products comes in same format, i.e. id-department-name-price-stock \n.
Use the jUnit test below to test your code. You can certainly modify how you read the product.txt file (may be other powerful string readers).
#Test
public void test() {
try {
List<String> productLines = Files.readAllLines(java.nio.file.Paths.get("./testData/product.txt"), StandardCharsets.UTF_8);
for (String line: productLines)
Product product = new Product();
String[] tokens = line.split("-");
product.setId(tokens[0]);
product.setDepartment(tokens[1]);
product.setName(tokens[2]);
product.setPrice(tokens[3]);
product.setStock(tokens[4]);
System.out.println(product.toString())
}
} catch (IOException e) {
e.printStackTrace();
}
}
For future readers.
I had double quotes surrounding my csv (comma separated values) file.
And had some doubles and ints.
I also has going nuts trying to find a "bad line" and the value that was barfing.... in the csv file. Thus my exception with a decent message.
My "delimiter" is a comma and carriage return. And I deal with the double quotes "at the column level".
Here is what I came up with.
/* I know, a java example with the imports listed out ! shocking !! */
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
private void loadFromFile() {
Collection<MyCustomObject> items = new ArrayList<MyCustomObject>();
int lineNumber = 0;
String nextValue = "";
try {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("MyFile.txt").getFile());
Scanner input = new Scanner(file)
.useDelimiter(",|\\R")
.useLocale(Locale.ENGLISH);
;
/* skip the header */
input.nextLine();
while (input.hasNext()) {
lineNumber++;
nextValue = input.next().replace("\"", "");
String zipCodeValue =nextValue;
nextValue = input.next().replace("\"", "");
String city = nextValue;
nextValue = input.next().replace("\"", "");
String usaState = nextValue;
nextValue = input.next().replace("\"", "");
double latitude = Double.valueOf(nextValue);
nextValue = input.next().replace("\"", "");
double longitude = Double.valueOf(nextValue);
nextValue = input.next().replace("\"", "");
int population = Integer.valueOf(nextValue);
items.add(new MyCustomObject(zipCodeValue, city, usaState, latitude, longitude, population));
}
} catch (Exception ex) {
throw new RuntimeException(String.format("Line number '%s, nextValue '%s''", lineNumber, nextValue), ex);
}
}
Sample text (csv) file:
"ZIPCODE","CITY","STATE","LATITUDE","LONGITUDE","POPULATION"
"06778","NORTHFIELD","CT",41.707,-73.105,555
"06779","OAKVILLE","CT",41.595,-73.081,777
"06782","PLYMOUTH","CT",41.657,-73.041,888

How to avoid using dynamic variables / a billion if statements in Java?

So, since dynamic variables aren't a thing in Java, and if statements will be horribly unwieldy, was looking for help converting this code block into a more concise one.
I looked into hashmaps, and they just didn't seem quite right, it's highly likely I was misunderstanding them though.
public String m1 = "Name1";
public String m1ip = "192.1.1.1";
public String m2 = "Name2";
public String m2ip = "192.1.1.1";
public String req;
public String reqip;
... snip some code...
if (requestedMachine == 1)
{ req = m1; reqip = m1ip;}
else if (requestedMachine == 2)
{ req = m2; reqip = m2ip;}
else if (requestedMachine == 3)
{ req = m3; reqip = m3ip;}
else if (requestedMachine == 4)
{ req = m4; reqip = m4ip;}
else if (requestedMachine == 5)
{ req = m5; reqip = m5ip;}
requestedMachine is going to be an integer, that defines which values should be assigned to req & reqip.
Thanks in advance.
Define a Machine class, containing a name and an ip field. Create an array of Machine. Access the machine located at the index requestedMachine (or requestedMachine - 1 if the number starts at 1):
Machine[] machines = new Machine[] {
new Machine("Name1", "192.1.1.1"),
new Machine("Name2", "192.1.1.1"),
...
}
...
Machine machine = machines[requestedMachine - 1];
First, create a Machine class:
class Machine {
String name;
String ip;
//Constructor, getters, setters etc omitted
}
Initialize an array of Machines:
Machine[] machines = ... //initialize them with values
Get the machine corresponding to requestedMachine:
Machine myMachine = machines[requestedMachine];
This is a great candidate for an enum:
/**
<P>{#code java EnumDeltaXmpl}</P>
**/
public class EnumDeltaXmpl {
public static final void main(String[] ingo_red) {
test(MachineAction.ONE);
test(MachineAction.TWO);
test(MachineAction.THREE);
test(MachineAction.FOUR);
}
private static final void test(MachineAction m_a) {
System.out.println("MachineAction." + m_a + ": name=" + m_a.sName + ", ip=" + m_a.sIP + "");
}
}
enum MachineAction {
ONE("Name1", "192.1.1.1"),
TWO("Name2", "292.2.2.2"),
THREE("Name3", "392.3.3.3"),
FOUR("Name4", "492.4.4.4"),
FIVE("Name5", "592.5.5.5");
public final String sName;
public final String sIP;
private MachineAction(String s_name, String s_ip) {
sName = s_name;
sIP = s_ip;
}
}
Output:
[C:\java_code\]java EnumDeltaXmpl
MachineAction.ONE: name=Name1, ip=192.1.1.1
MachineAction.TWO: name=Name2, ip=292.2.2.2
MachineAction.THREE: name=Name3, ip=392.3.3.3
MachineAction.FOUR: name=Name4, ip=492.4.4.4
Thee best choice you have is to build an array of machines with IP, Name etc..then you only need to find the machine required into the array.
public class Machine(){
private String name, ip;
public Machine(String name, String ip){
this.name=name;
// You can check a valid ip
this.ip=ip;
}}
public class Machines(){
private Machine[] machines;
private int number_of_machines;
public Machines(){
//define number_of_machines for your array and length of itself
}}
main()
Machine[] Machines = new Machine[number_of_machines];
Machine m1 = new Machine(String name, String ip);
.
.
.
Machine mn = new Machine(String name, String ip);
int number=5;
for(int i=0; i<number_of_machines; i++){
if (machines[number]<number_of_machines){
System.out.println("There is no machine with that number");
}else if (machines[number]==number_of_machines-1){
System.out.println("That is the choosen machine");
}
}
}
If your id values are not necessarily integers or if they are not a continuous sequence from 0 forward, you could also use a HashMap. Something like
HashMap<Integer, Machine> machines = new HashMap<>();
machines.put(1, machine1);
machines.put(7, machine7);
...
to get the desired value
Machine machine7 = machines.get(7);
You can replace the key with a String or whatever you like if needed. Your id values also do not need to go 0,1,2,3,4,5, ... as they need to if you are going with an array.

java object creation

public class ServersList {
private Host host;
private Server server;
private InfoList infoList;
private List<AbcInformation> abcInformation;
#XmlElement(name = "Host")
#JsonProperty("Host")
public Host getHost() {
return this.host;
}
//Get Set functions for all object
}
We have the above class. It contains some object of other classes and get/set methods as shown above. We are parsing an XML file and creating an array of ServersList class. For example,
ServersList[] serversArray = new ServersList[count];
for (int index = 0; index < count; index++) {
serversArray[index] = new ServersList();
serversArray[index].setInfoList(serConfig
.getInfoList());
serversArray[index].setHost(serConfig
.getHost());
serversArray[index].setServer(serConfig
.getServer());
serversArray[index].getHost().setCid(
listResponse.getHost().get(index).getCid());
serversArray[index].getHost().setCName(
listResponse.getHost().get(index).getCname());
serversArray[index].getHost()
.setCurrentName(listResponse.getHost().get(index)
.getCurrentName());
serversArray[index].getHost().setHostName(listResponse.getHost().
get(index).getName());
serversArray[index].getHost().setHostUuid(
listResponse.getHost().get(index).getId());
}
Our problem is after the for loop all values of the serversArray array will be same (may be with last element in the xml). While debugging I understand that, every iteration the value of every rows are changed the values of current row. Can you suggest a solution for this?
Try doing this, should work.
public static void main(String[] args) {
ServersList sList=null;
int count=10;
ServersList[] serversArray = new ServersList[count];
for (int index = 0; index < count; index++) {
sList = new ServersList();
sList.setHost(....);
//..........other setter...........
serversArray[index] = sList;
}
for (ServersList serversList : serversArray) {
System.out.println(serversList.getHost());
}
}
Finally I found the solution. I have added copy constructors for the following classes
ServersList, Host, Server, InfoList, AbcInformation

Categories