Saving data from scanner to string multidimensional array - java

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.

Related

How to add items to array of objects using loops

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.

Array inside ArrayList Loop to fake DB

I am learning Java so I am trying to create a very basic program that can create, contain, show and erase accounts.
The thing is I thought about creating an ArrayList (because it can grow itself instead of putting a counter, I guess) which contains a normal Array with all the variables with the information of this customers inside.
So, basically the arrayList should contain the columns and grow when needed to register a new customer and the Array (with a fixed lengt) to save all the data of the customer.
I already looked and read a lot but not able to find a solution.
The code below is the customer creation method, I need to understand how can I use a for loop to fill the arrays and then search, erase or edit a customer based in ID.
Thanks in advance!
public class CustomersDB {
private static Scanner scanner = new Scanner(System.in);
private ArrayList<String[]> custList = new ArrayList<String[]>();
String[] newCustomer = new String[9];
System.out.println("Name: ");
newCustomer[0] = scanner.nextLine();
setCustName(newCustomer[0]);
System.out.println("Surname: ");
newCustomer[1] = scanner.nextLine();
setCustSurname(newCustomer[1]);
System.out.println("ID: ");
newCustomer[2] = scanner.nextLine();
setCustSurname(newCustomer[2]);
custList.add(newCustomer);

How to append data into a String list in Java

I am new to Java and Here is my code.
String[][] datas={{"a","b","c"},{"d","e","f"},{"g","h","i"}};
String[] onedata={"j","k","l"};
the thing I want to do here is that, I want to append the onedata into datas at last index value.
Please help let me know that how can I do this.
You can use an ArrayList because their sizes are mutable. For example:
String[][] datas={{"a","b","c"},{"d","e","f"},{"g","h","i"}};
List<String[]> datasList = new ArrayList<>(Arrays.asList(datas));
String[] onedata = {"j","k","l"};
datasList.add(onedata);
datas = datasList.toArray(new String[datasList.size()][]);
The things you are dealing with are arrays (String[]) and multidimensional arrays (String[][]) in Java, not lists. Their length is fixed. Therefore to append a new item to an array in such way that the length increases (so not by replacing the last item in the current array) you would need to create a new array with length n+1, assign the old values to the first n indices and then the new value to the index n+1.

For Loop doesnt add point to an array

I have the following for loop which looks through a string ArrayList of results, each item in the string is seperated by "::":
ArrayList<String> resultsArray = MyClass.results;
Integer numPoints = resultsArray.size();
for (int i =0;i<numPoints;i++){
String[] pointDetails = resultsArray.get(i).split("::");
String pointName = pointDetails[0];
String pointDescription = pointDetails[1];
String coordinates = pointDetails[2];
//Turn coordinates into geopoints
String coord[] = coords.split(",");
Integer lng= (int) (Double.valueOf(coord[0]) * 1000000);
Integer lat = (int)(Double.valueOf(coord[1])*1000000);
GeoPoint gPoint = new GeoPoint(lng,lat);
arrayPointName = new ArrayList <String>();
arrayPointDescription = new ArrayList <String>();
arrayPointCoords=new ArrayList<GeoPoint>();
arrayPointName.add(pointName);
arrayPointDescription.add(pointDescription);
arrayPointCoords.add(gPoint);
}
I know I have 20 points in the initial string ArrayList and have printed out its size to check this. However, when I print out the new arraylists, such as arrayPointName, they only contain one point. Any idea on why this is?
Look at this code:
arrayPointName = new ArrayList <String>();
arrayPointDescription = new ArrayList <String>();
arrayPointCoords=new ArrayList<GeoPoint>();
Those three statements - assigning new, empty ArrayList references to your variables - are being executed on every iteration of your loop.
They should come before your loop instead: you only want to initialize the variables once (creating the three lists) and then add a new item on each iteration.
As a side note, populating multiple collections like this is normally a bad idea. It's usually better to create a single type which encapsulates the related data (name, description, coordinates in this case) and then create a single collection of items of that type. That's usually a lot easier to work with.
you used coords as an ArrayList Without initiate it .Also you initiate for each iteration arrayPointName, arrayPointDescription and arrayPointCoords that's why they lost the value created in the previous iteration. they should be initiate juste one time before starting the loop
it will be easy to help you if you give us a sample of resultsArray strring.

Getting rid of excess while statement

Could anybody have a look at this snippet of code and and tell me if there is a way to amalgamate the two while statements into one?
public static void main(String[] args) throws IOException
{
BufferedReader fileInput;
fileInput = new BufferedReader(new FileReader("information.txt"));
int countOfClients = 0;
while (fileInput.ready())
{
fileInput.readLine();
countOfClients ++;
}
int totalClients = countOfClients ;
Client[] clientDetails = new Client[totalClients];
int clientNumber = 0;
while (fileInput.ready())
{
String currentLineOfText = fileInput.readLine();
String clientName = currentLineOfText.substring(0, 19);
String gender = currentLineOfText.substring(20,21);
char clientGender = gender.charAt(0);
int clientAge = Integer.parseInt(currentLineOfText.substring(22,24));
String clientInterests = currentLineOfText.substring(25);
clientDetails[clientNumber] = new Client(clientName, clientGender, clientAge, clientInterests);
clientNumber++;
}
The first while statement is reading all the lines in the text, so it knows how many elements in the object array it needs.
The array clientDetails of class Client[] is then created.
The second while statement populates that array.
Can I avoid using two while statements?
Note: This is for an assignment and I have to use arrays.
As they're all saying, use an ArrayList to store the items.
If memory is an issue, you can use ArrayList.toArray() to trim it down to the bare bones.
If efficiency is an issue, you probably shouldn't be reading from a file in the first palce.
You could use an ArrayList instead of an array and simply use:
list.add(new Client(...));
If you really need an array, you can always call:
Client[] array = list.toArray();
Why create an array ? Why not have one while loop that creates an ArrayList and then (if you need an array) extract the resultant array from that using ArrayList.toArray() ?
You can avoid two while loops by changing Client[] to ArrayList();
Example:
List<Client> clientDetails = new ArrayList<Client>();
int clientNumber = 0;
while (fileInput.ready())
{
String currentLineOfText = fileInput.readLine();
String clientName = currentLineOfText.substring(0, 19);
String gender = currentLineOfText.substring(20,21);
char clientGender = gender.charAt(0);
int clientAge = Integer.parseInt(currentLineOfText.substring(22,24));
String clientInterests = currentLineOfText.substring(25);
clientDetails.add( new Client(clientName, clientGender, clientAge, clientInterests));
}
Note: Hand edited, there may be syntax errors.
If you really can't use the pre-written ArrayList class, you could always effectively re-implement it (or at least the relevant bits of it) yourself.
The key technique is to take a guess at the size of the array you might need, define an array that size, and, if you find it is too small, create a bigger array and copy all the existing values from the old to the new array, before continuing in the space that is left over.
At the other end of the loop, you might be in for yet another step, and shrink the array again (by declaring a smaller array and copying values over) so you have no empty spaces left.
Or, as recommended by all the other answers, just use an ArrayList, which already does exactly this for you...

Categories