How to add items to array of objects using loops - java

I've got a multiple student objects I want to write into with a CSV file containing their details. I've set each row of the CSV file to an array then was going to split each entry of the array into another array and use that to set the attributes of the object. However, each time I try, I get a NullPointerException.
String studentCSV = "src\\CSV Files\\Students.csv";
Student[] student = new Student[CSV_Reader.count(studentCSV)];
String[] values = CSV_Reader.read(studentCSV);
for(int i=0;i<values.length;i++){
String[] line = values[i].split(",");
student[i].addPerson(line[0],line[1],line[2],line[3]);
student[i].addStudent(line[4],line[5],line[6]);
}

int n=10; // for example
Student[] student = new Student[n];
//now you just allocate memory for array
for(int i=0;i<student.length;i++){
student[i]=new Student();
// here you assign student to your any element of array
}
// now you can do anything with elements of your student array

Most likely, there is a line with information (or separator) missing and trying to access that index causes the exception. You should check that first (simply print out the lines in the loop at first and whatever causes the error will be the last to print).
Otherwise: please show the full error log and point out on which line the error occurs.

Related

Arraylist inside arraylist, how do I clear the last

I use while loop to read a text file and create new arraylists out of portions of the text file and then place those arraylists inside another arraylist. My problem is that I don't know how to add my temporary arraylist parse into the mainAList and then clear it for the next loop without affecting all the parse arraylists inside the arraylist<arraylist> mainAList. More info inside the comments below in the code.
This is a sample code, it is from larger file. It is shortened but has all the moving parts
ArrayList<ArrayList<String>> mainAList = new ArrayList<ArrayList<String>>();
ArrayList<String> parse = new ArrayList<>();
try (Scanner filereader = new Scanner(Paths.get("name_of_file.txt"))) {
while (filereader.hasNextLine()) {
parse.add(filereader.nextLine());
if (parse.get(parse.size()-1).length() == 0 || !filereader.hasNextLine()) {
// if the file reader detects empty line or has no more lines
// the arraylist called parse gets added to the mainAList
mainAList.add(parse);
}
parse.clear();
// here is my problem. How do I clear parse so for the next patch of lines
// so I don't add the same things + more into the next slot of mainAList
// every time the loop runs?
// I understand my issue is not how to correctly clear the parse but
// how to add the arraylists correctly into the mainAList so I can alter them individually
}
}
The file that is read is like this:
a
b
c
d
f
g
h
i
j
k
l
etc..
There are two problems with your current approach:
parse will use the same reference for all inner ArrayLists, so when you call parse.clear() it will empty all inner lists of your mainAList. This can be solved by creating a copy of the parse list when you add it (i.e. mainAList.add(new ArrayList<>(parse));)
You want to clear the list inside the if as well, after you've added the copy to your mainAList.
In addition, I assume you don't want the empty lines added to the individual inner Lists, so you could read the line first, and either add the entire list to mainAList and clear parse inside the if-statement, or add the line to the parse-list.
A slightly better alternative, is to just create a new list instead, so you won't need the clear and creating a copy of the list.
In total:
ArrayList<ArrayList<String>> mainAList = new ArrayList<ArrayList<String>>();
ArrayList<String> parse = new ArrayList<>();
try (Scanner filereader = new Scanner(System.in)) {
while (filereader.hasNextLine()) {
String line = filereader.nextLine();
if (line.length() == 0 || !filereader.hasNextLine()) {
// if the file reader detects empty line or has no more lines
// the arraylist called parse gets added to the mainAList
mainAList.add(parse);
// and then a new parse-list is created for the next group of inputs:
parse = new ArrayList<>();
} else{
parse.add(line);
}
}
}
Try it online.
Try this instead of clearing the list everytime.
ArrayList<ArrayList<String>> mainAList = new ArrayList<ArrayList<String>>();
try (Scanner filereader = new Scanner(Paths.get("name_of_file.txt"))) {
while (filereader.hasNextLine()) {
ArrayList<String> parse = new ArrayList<>();
parse.add(filereader.nextLine());
if (parse.get(parse.size()-1).length() == 0 || !filereader.hasNextLine()) {
mainAList.add(parse);
}
}
}
Your problem is that your mainAList will be empty in the end because objects are reference types. In order to fix that problem, you have to add a copy of parse to the mainAList and not the parse arraylist itself
replace this line
mainAList.add(parse);
with this
mainAList.add(new ArrayList<>(parse));

Problem filling an array with my JSON file information

I have a JComboBox that I want to be filled with an array of my json file information:
This is my json:
{"Agencias":[{"nombre":"OpenWorld C.A","agenciaDir":"Los teques","telefono":"45789658","nombreContacto":"daniel","telefonoContacto":"34567321"}]}
I'll show you 2 versions of the same array-fill-function: the first version doesn't work, and is what im trying to do; the second version do not fill the array (what I need) but it works in my combobox. This is the first version:
public String[] llenarComboboxAgencias() {
String[] array1 = null; //i create a new null array
JSONArray listaAgencias = agencias.getJSONArray("Agencias"); //get into my JSon "Agencias" array
for(int j=0;j<listaAgencias.length();j++) { //start reading "Agencias array"
JSONObject agencia = listaAgencias.getJSONObject(j); //JSONObject for each object in my "Agencias" array.
this.string1=agencia.getString("nombre"); //I save my JSONObect "nombre"(name) in a string
array1[j]=agencia.getString("nombre"); //I give to my "array1"[position] the information of the object name
}
return array1; //Return my string array1
}
Now, what happens in this already shown code, is a nullpointerException in the line: array[j]=agencia.getString("nombre");. The question is not the same thing of this post Link, because I did an other code without filling my array, with the same coding logic (I think) and do not have problems.
So, this is my second version with an already filled array. And it works perfectly!:
public String[] llenarComboboxAgencias(){
JSONArray listaAgencias = agencias.getJSONArray("Agencias"); //get into my JSon "Agencias" array
for(int j=0;j<listaAgencisa.length();j++) { //start reading "Agencias array"
JSONObject agencia = listaAgencias.getJSONObject(j); //JSONObject for each object in my "Agencias" array.
this.string1=agencia.getString("nombre"); //I save my JSONObect "nombre"(name) in a string
//this is where my code changes: now im printing all my "names" on the console
System.out.println(string1);
}
//and this is the most important change: im not filling my array, this is an already filled one!
String[] array1= {"Hello","Friend"};
return array1; //return my already filled array
}
This code, in console it shows all my JSON "agencias" names, and my JFrame JCombobox, gets the filled array as options without getting any problem/error.
So the problem is in the first code where I tried to fill my array1[], but I don't get why? a string[] isn't an object, and im starting the "fill" in the first array1[] box :0, and otherwise the array isn't empty, it have already a string on it my Agencia's "nombre" (OpenWorld C.A)
My question is simple: why my first code doesn't work, and why my second on does? how can I get a code to fill properly my array, and return it like the second version does?
Your array is null: String[] array1 = null;. Then you try to assign to the array: array1[j]=agencia.getString("nombre");. That's why you get a NPE.
You need to instantiate your array.
String[] array1 = new String[listaAgencisa.length()];
Alternately, use an ArrayList instead.

Variable length objects and using traditional for loop

In one of my methods, I need to pass objects as variable length parameters.
However, first I need to process the last object and then based on that many other processing will be done. I could not figure out how to use the index for each of the items in the variable argument list using traditional for loop and then index. So I used below code. Is this the right method to copy the object reference to another Array or ArrayList as I did? Otherwise what is the best method to access the specific object first and then loop through all other objects.
public static int generateConnectedPatterns(String endStr,Moorchana.MoorchanInnerClass...totalPatterns) {
// First copy all the objects to new ArrayList or Array of objects
ArrayList <Moorchana.MoorchanInnerClass> objectList = new ArrayList<>();
objectList.addAll(Arrays.asList(totalPatterns));
//Temporarily use lastObject variable for convenience.
Moorchana.MoorchanInnerClass lastObject = objectList.get(objectList.size()-1);
// Split the last input string into swaras
ArrayList<Integer> indices = new ArrayList<>();
ArrayList<String> tempPatternList = new ArrayList<>();
splitInputPatternIntoArrayList(tempPatternList , indices, lastObject.rawInputString);
if (Moorchana.validatePresenceInSwaraPool(endStr, lastObject.returnOuterObjectRef().swaraPool) == -1) {
return (-1);
}
// Get the index of the ending String
int indexofEndStr = lastObject.returnOuterObjectRef().getSwaraIndex(endStr);
// Now get the number of patterns to be generated.
int count = lastObject.returnOuterObjectRef().getPatternCount(indices, indexofEndStr);
// Now Do remaining programming here based on the count.
return(Constants.SUCCESS);
}
A varargs is basically an array.
Once you checked for null and length, you can access the last element just as you would with an array.
On the other hand, Arrays.asList returns a fixed-size list, which means you will not be able to manipulate its size later on, so beware of UnsupportedOperationExceptions.
In short, you can use the varargs as array and reference the last element once the necessary checks are performed.
Treat totalPatterns as an array.
To identify the last element: totalPatterns[totalPatterns.length-1]
for iteration, you could use an enhanced for loop.
for ( Moorchana.MoorchanInnerClass d : totalPatterns){...}
Note: Do a null check before you process the array, if you are not sure of the input being passed.

Saving data from scanner to string multidimensional array

I need to save data such as name, surname, etc... from different clients, and then to have a possibility to choose one of them and view all his data.
I tried with multidimensional array (using loop), but its not working.
Here is the code I tried:
void objectsMaking(){
TeleAddressData teleAddressData = new TeleAddressData();
for(int i=0; i<teleAddressData.tableOfNames.length; i++){
System.out.println(teleAddressData.tableOfNames[i]);
String[] list = new String[howManyClients];
Scanner scanner1 = new Scanner(System.in);
teleAddressData.tablicaDanych[howManyClients-1][i] = scanner1.nextLine();
}
I made an object of TeleAddressData class, because there is an array with names such as name, surname ect. So loop "for" takes those names.
teleAddressData.tablicaDanych[howManyClients-1][i] = scanner1.nextLine();
this part should store scanner lines in certain array's cells but I think it is not working.
Any ideas?
You shouldn't have String[][] here, you should have some meaningful object (Client?) and have Client[].
Beyond that it seems very odd as you are constantly making a new list, and then never assigning that new list into your main data set, and then assigning a value to a probably never initialized array.

Dynamically store objects in an unallocated object in java

I am stuck in a problem where i have to allocate string objects in an array of strings But the problem is i don't know how many string objects i will be putting in this array.
CODE
static String[] decipheredMessage;
static int pointer=0;
// in another function i have this code
if(sentenceFormationFlag==true) {
// System.out.println(" " + word); // prints the words after sentence formation
// add the words to an array of strings
decipheredMessage[pointer] = new String();
decipheredMessage[pointer++] = word;
return true;
What i have done here is i have declared an array of strings and since i don't know how many strings my array is going to contain i dynamically create string objects and assign it to the array.
ERROR
$ java SentenceFormation
arms
Exception in thread "main" java.lang.NullPointerException
at SentenceFormation.makeSentence(SentenceFormation.java:48)
at SentenceFormation.makeSentence(SentenceFormation.java:44)
at SentenceFormation.makeSentence(SentenceFormation.java:44)
at SentenceFormation.main(SentenceFormation.java:16)
I don't know why i am getting this problem can anybody help me with this.
Thanks in advance.
Dynamic arrays do not work in Java. You need to use one of the fine examples of the collections framework. Import java.util.ArrayList.
static ArrayList<String> decipheredMessage=new ArrayList<>();;
static int pointer=0;
// in another function i have this code
if(sentenceFormationFlag==true) {
// System.out.println(" " + word); // prints the words after sentence formation
// add the words to an array of strings
decipheredMessage.add(new String());
decipheredMessage.add(word);
return true;
You can use a List implementation like ArrayList if you don't know how many elements your array will have.
static List<String> decipheredMessage = new ArrayList<>();
...
decipheredMessage.add("my new string");
Check out the List documentation (linked above) to see what APIs are available.
If you are using Java 5 or 6, you'll need to specify the type in the angled brackets above, i.e. new ArrayList<String>().
Try something like this, and read about List
List<String> decipheredMessage = new ArrayList<String>();
static int pointer=0;
// in another function i have this code
if(sentenceFormationFlag==true) {
// System.out.println(" " + word); // prints the words after sentence formation
// add the words to an array of strings
decipheredMessage. add("string1");
decipheredMessage.add("string2");
return true;

Categories