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);
Related
first of all thanks for the help.
I'm aware of the Reference passing mechanism of java and I need to read one million of lines (a word + a_list_of_integers each line) from a text file and put them in some structures that are class attributes, one hashmap and two arraylist.
The problem is that with the code below, written to save memory reusing the list "termine_frequenza", when I try to get and element from the "frequency" arraylist or the "dictionaryMarTD" hashmap, the list that returns is always the last list that I added.
Adding the declaration of the "Arraylist termine_frequenza" into the While obviously solves the problem but I receive a prevedible "GC overhead limit exceeded" error because of multiple declaration (i tried to increase heap o disable it, but GC fills the cpu capacity trying to free memory.
The question is simple: how can I save memory and at the same time have a correct reading? Thanks.
//Class attributes
private HashMap<String, ArrayList> dictionaryMapTD;
private ArrayList<String> words;
private ArrayList<ArrayList> frequency;
//This is the code of a method of the class that reads from a file
br = new BufferedReader(new FileReader("dictionary.txt"));
s = br.readLine();
String[] splitted;
ArrayList<Integer> termine_frequenza = new ArrayList<>();
while(s!=null)
{
termine_frequenza.clear();
splitted = s.split(" ");
words.add(splitted[0]);
for (int i = 1; i < splitted.length; i++)
{
termine_frequenza.add(Integer.valueOf(splitted[i]));
}
frequency.add(termine_frequenza);
dictionaryMapTD.put(splitted[0], termine_frequenza);
s = br.readLine();
}
//END
Change your XMS/XMX parameters in your eclips.ini file.
I set it -Xms256m-Xmx7024m for 3000000
If it has no effect then try to modify that parameters for application
In your eclips go to
RunConfigurations->Arguments->VM Arguments
for your application and put
-Xms256m
-Xmx7024m
Then in your code move
termine_frequenza = new ArrayList<>();
inside while and remove
termine_frequenza.clear();
GC should not complain
In my case It runs for 7000000 records
Let me know if it helps
Quick overview of our assignment:
User needs to enter grades received. We do not know how many grades user needs to enter. If the user enters "-1" thats when we know the user is done entering grades.
Problem is how do you use a counter and assign values to an array in the same loop? I would rather not have to ask the user to enter all values twice (Once to get array size and the second time to assign grades to index positions).
Our professor gave us a handout that tells us to basically guess the size of the array and hope for the best. I refuse to believe that's the only solution.
Any help would be appreciated. Thanks.
You can't make dynamic array in java.
For that you will have to use List or ArrayList.
We will have to provide the size of array before application run or at coding time, while arrayList gives us facility to add data while we need it, so it's size will automatically increased when we add data.
Example :
import java.util.*;
public class ArrayListDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " + al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}
this example is from here.
UPDATE :
When you define your list as:
List myList = new ArrayList();
you can only call methods and reference members that belong to List class. If you define it as:
ArrayList myList = new ArrayList();
you'll be able to invoke ArrayList specific methods and use ArrayList specific members in addition to those inherited from List.
List is not a class it is an interface. It doesn't have any methods implemented. So if you call a method on a List reference, you in fact calling the method of ArrayList in both cases.
Using some kind of List is a better choice, as it basically does what you want (can grow and shrink), in fact, ArrayList is just that, a dynamic array.
You can hand roll your own if you can't use a List using System.arraycopy
For example, this will grow or shrink an array to match the size you provide...
public String[] updateArray(String[] src, int size) {
String[] dest = new String[size];
if (size > src.length) {
System.arraycopy(src, 0, dest, 0, src.length);
} else {
System.arraycopy(src, 0, dest, 0, size);
}
return dest;
}
Again... List is easier...
Building a dynamic array involves these basic steps:
-Create an array of a fixed capacity.
-When the size of the array (# of elements added) approach the capacity, create a new array (usually doubling the capacity), and copy all the old elements to the new array.
A linked list is the most efficient for your task of building the array (done in O(1) time). However, accessing elements for inserting and deleting in a linked list is not efficient (O(n) time). Imagine having to move through the whole list to get to the last element. Building the dynamic array is less efficient, because of the need to re-size the array as it grows. Inserting and deleting elements is less efficient because of need to move all the elements after to make room or fill the gap. However accessing an element in an array is efficient (O(1) time) and there are big advantages when it comes to sorting.
The Java ArrayList is an implementation of a dynamic array. You could also implement your own.
If you can't use an ArrayList, or any kind of dynamic list at all, then one solution would be this:
StringBuilder sb = new StringBuilder();
Scanner scanner = new Scanner(System.in);
int j;
while((j=scanner.nextInt()) !=-1){
sb.append(j + " ");
}
String []numbers = sb.toString().split(" ");
int[] grades = new int[numbers.length];
for(int i=0;i<numbers.length;i++){
grades[i] = Integer.parseInt(numbers[i]);
}
As you can see, I'm putting the input in a stringbuilder object, then I parse it in an array of strings, and convert that array in an integer array.
I hope this helps.
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.
Hey I'm having some trouble with Java (shocker (sarcasm)). I have an array of strings, and what I would like to do is iterate through the array, using each string to make a new object. Is this legal?
String[] arrayOfNames = String[3];
goGetNamesToFillTheArray();
for(i = 0; i < arrayOfNames.length; i++) {
Person arrayOfNames[i] = new Person();
}
If it's not legal for me to do that, how would I do something like that?
For clarification, I want to have several objects of type person. If the array contains the entries jon and sally, I could later later in the program have jon.doSomething() as well as sally.doSomething()
Assuming you want to create an array of Persons and filled them with the names:
String[] arrayOfNames = new String[3];
goGetNamesToFillTheArray();
Person[] arrOfPerson = new Person[arrayOfNames.length];
for(int i = 0; i < arrOfPerson.length; i++) {
arrOfPerson[i] = new Person(arrayOfNames[i]);
}
Several things:
String[] arrayOfNames = String[3];
is incorrect. You need to allocate memory via the new operator:
String[] arrayOfNames = new String[3];
To my knowledge, there's no way to dynamically create identifiers. I have a feeling that what you're actually trying to do is to use the name from your array and in some way use it in Person.
To do this, you can have your constructor take a String as its parameter. If you do this, you can change your code to be:
goGetNamesToFillTheArray();
Person[] people = new Person[3];
for(i = 0; i < 3; i++)
{
people[i] = new Person(arrayOfNames[i]);
}
NB:I used 3 in the above code since you did, but you should use a constant or some sort of variable, ie final int LENGTH = 3;.
You should show us the Person class. But conceivably this class will have a constructor that takes a String. Perhaps you should pass in the String from the array into the constructor.
Edit: as Ran Eldan shows you with his answer. 1+ to that answer!
Edit: Regarding your recent edit to your question:
You state:
For clarification, I want to have several objects of type person. If the array contains the entries jon and sally, I could later later in the program have jon.doSomething() as well as sally.doSomething()
You're trying to give variables the names of Strings, and you shouldn't try to do this as this is not how Java works. Variable names are not all that important and certainly not as important as you think they are, but rather object references are what really matter. If you need to associate an object with a String, use a Map, but I don't think you even need to do this. Just use an array or ArrayList. This same type of question has been asked here umpteen million times, and if you search a little for it, you'll find the same answers.
If the question is to create the Object from String class name, You can use code below:
String className = "InstanceFromString";
InstanceFromString test = (InstanceFromString)Class.forName(className).newInstance();
System.out.println(test);
I know the title sound confusing and thats because it is. its a bit long so try too stay with me.
this is the layout i have my code designed
variables
constructor
methods.
im trying too fill a Jlist full on names. i want too get those names using a method. so here goes.
in my variables i have my JList. its called contactNames;
i also have an array which stores 5 strings which are the contacts names;
heres the code for that anyway
String contact1;
String contact2;
String contact3;
String contact4;
String contact5;
String[] contactListNames;
JList contactList;
simple enough. then in my constructor i have the Jlist defined to fill itself with the contents of the array
String[] contactListNames = new String[5];
JList contactList = new JList(contactListNames);
fillContactList();
that method fillContactList() is coming up shortly.
now heres where stuff gets balls up.
ive created three different methods all of which havent worked. basically im trying to fill the array with all of them.
this is the simplest one. it doesnt set the Jlist, it doesnt do anything compilicated. all it trys too do is fill the array one bit at a time
public void fillContactList()
{
for(int i = 0;i<3;i++)
{
try
{
String contact;
System.out.println(" please fill the list at index "+ i);
Scanner in = new Scanner(System.in);
contact = in.next();
contactListNames[i] = contact;
in.nextLine();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
unfortunately this doesnt qwork. i get the print out to fill it at index 0; i input something and i get a nice big stack trace starting at
contactListNames[i] = contact;
so my question in short is
why cant i fill the array from that method.
***********************************************888 ***********************************************888
stack trace by request
please fill the list at index 0
overtone
please fill the list at index 1
java.lang.NullPointerException
at project.AdminMessages.fillContactList(AdminMessages.java:410)
at project.AdminMessages.<init>(AdminMessages.java:91)
at project.AdminUser.createAdminMessages(AdminUser.java:32)
at project.AdminUser.<init>(AdminUser.java:18)
at project.AdminUser.main(AdminUser.java:47)
To define an array in a constructor you can do something along these lines,
// if values are predefined, you can explicitly fill the array
String[] contacts = {"Bill Gates", "Steve Jobs", "Jon Skeet"};
// or this way, both will work.
String[] contacts = new String[2];
Looking at JList from the Java Doc's you can most certainly pass in an array to JList
String[] data = {"one", "two", "three", "four"};
JList dataList = new JList(data);
You are getting NullPointerException because the array, contactListNames is not initialized, you would need to initialize it.
You define an array in a constructor just like you would any other variable. So, it would look something like:
// define an array of size 3
String[] contactListNames = new String[3];
The reason you are getting exceptions is because you don't actually initialize the array. You declare it but you never set it to a value (or give it a size). You should post the stack trace of the error but I suspect it's a NullPointerException.
Then in my constructor i have the
Jlist defined to fill itself with the
contents of the array
String[] contactListNames = new String[5];
JList contactList = new JList(contactListNames);
fillContactList();
What you're doing here is creating new local variables that are shadowing the ones defined in your class.
Change it to:
contactListNames = new String[5];
contactList = new JList(contactListNames);
fillContactList();