Getting rid of excess while statement - java

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...

Related

Store an array within a 2d array Java

So why doesn't this work? Not really sure why this isn't possible- I just want to store an array of size 2 inside a 2d array.
I know this would be equivalent to setting storage[0][0] = array[0] and storage[0][1] = array[1], but just wondering why this is incorrect.
public class Test {
public static void main(String[] args) {
boolean[][] storage = new boolean[10][2];
boolean[] array = new boolean[2];
array[0] = true;
array[1] = false;
storage[0][] = array; //Why can't I do this?
}
}
Thanks in advance
You have a stray pair of brackets in your assignment. Just use
storage[0] = array;
First of all boolean[][] storage = new boolean[10][2] declares an array and initialise it.
So, you have created 11 arrays. One of boolean[] element type and 10 of boolean type.
It's good, If you want to access it's members directly, but if you create an inner array lately with new boolean[], it's an overhead.
Use boolean[][] storage = new boolean[10][]; instead.
Then, you can access it's elements, which are boolean[] type, and assign your array to it.
storage[0] = array;
Your problem is the stray square brackets(as I'm sure you know). Your code should look like this:
storage[0] = array;
The previous answers did not really explain why though, so that's what I'll do.
What your trying to do is make the first position(storage[0]) hold the same value as array. array is 1 dimensional, so it can only be part of storage, which is 2 dimensional.

Creating objects with names from string[]

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);

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.

How to add new Strings to a certain array

I got 4 arrays in my code and everytime a user writes something into the edittext I want to store that string in one of the array, I tried to use the toCharArray method but I don't know how to define the array where the string should be put in :S
String [] array7 = {"Hey","Was Up","Yeahh"};
TextView txtV1,txtV2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layouttry);
txtV1=(TextView)findViewById(R.id.textView1);
txtV2=(TextView)findViewById(R.id.textView2);
Bundle extras = getIntent().getExtras();
String value = extras.getString("Key"); // this value I want to add to the stringarray
If you need to add new elements I would suggest replacing your arrays with ArrayLists. This will let you use the add method to insert new elements. An example of this:
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("Text here");
In your code I can only see one array on Strings, so I'm not sure about what you actually need. I'll try my best though.
Your String array is hard-coded to have only three cells in it, and they are all full. If you want to put the string into any of these places, do this:
array7[0] = value; //or:
array7[1] = value; //or:
array7[1] = value;
If you want to add value to the array without deleting the existing values, you can do something like this:
//Create a new array, larger than the original.
String[] newArray7 = new String[array7.length + 1 /*1 is the minimum you are going to need, but it is better to add more. Two times the current length would be a good idea*/];
//Copy the contents of the old array into the new one.
for (int i = 0; i < array7.length; i++){
newArray7[i] = array7[i];
}
//Set the old array's name to point to the new array object.
array7 = newArray7;
You can do this in a separate method, so whenever you need to re-size your array you can use it. You should know that the classes ArrayList and Vector already implement this mechanism for you, and you can arrayList.add(string) as much as you want.

Remove a specific string from an array of string

I have an array like this:
String n[] = {"google","microsoft","apple"};
What I want to do is to remove "apple".
My problem is very basic,however,I searched the website and I found out that java doesn't really support the deleting feature from an array.I also heard to use Java Utils, because it's so simple to remove an item....I tried to find Java Utils on google, but almost all links are dead.
So finally...is there any way to remove a string from an array of string?
Even if I use an ArrayList I can't find a method to generate a random item in it! For ex: in a normal array I generate a string like this:
String r = myAL[rgenerator.nextInt(myAL.length)];
In an arraylist it doesn't work....maybe you know a solution...
Define "remove".
Arrays are fixed length and can not be resized once created. You can set an element to null to remove an object reference;
for (int i = 0; i < myStringArray.length(); i++)
{
if (myStringArray[i].equals(stringToRemove))
{
myStringArray[i] = null;
break;
}
}
or
myStringArray[indexOfStringToRemove] = null;
If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList<String>
myArrayList.remove(stringToRemove);
or
myArrayList.remove(indexOfStringToRemove);
Edit in response to OP's edit to his question and comment below
String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));
It is not possible in on step or you need to keep the reference to the array.
If you can change the reference this can help:
String[] n = new String[]{"google","microsoft","apple"};
final List<String> list = new ArrayList<String>();
Collections.addAll(list, n);
list.remove("apple");
n = list.toArray(new String[list.size()]);
I not recommend the following but if you worry about performance:
String[] n = new String[]{"google","microsoft","apple"};
final String[] n2 = new String[2];
System.arraycopy(n, 0, n2, 0, n2.length);
for (int i = 0, j = 0; i < n.length; i++)
{
if (!n[i].equals("apple"))
{
n2[j] = n[i];
j++;
}
}
I not recommend it because the code is a lot more difficult to read and maintain.
Arrays in Java aren't dynamic, like collection classes. If you want a true collection that supports dynamic addition and deletion, use ArrayList<>. If you still want to live with vanilla arrays, find the index of string, construct a new array with size one less than the original, and use System.arraycopy() to copy the elements before and after. Or write a copy loop with skip by hand, on small arrays the difference will be negligible.
You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3.
You'd be better off with a List<String>, e.g. an ArrayList<String>:
List<String> list = new ArrayList<String>();
list.add("google");
list.add("microsoft");
list.add("apple");
System.out.println(list.size()); // 3
list.remove("apple");
System.out.println(list.size()); // 2
Collections like this are generally much more flexible than working with arrays directly.
EDIT: For removal:
void removeRandomElement(List<?> list, Random random)
{
int index = random.nextInt(list.size());
list.remove(index);
}
import java.util.*;
class Array {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add("google");
al.add("microsoft");
al.add("apple");
System.out.println(al);
//i only remove the apple//
al.remove(2);
System.out.println(al);
}
}

Categories