java - Storing String sequence in arraylist - java

I am trying to create a list using the code below, that stores random binary strings. But everytime I print the string elements of list, all the string elements that are printed are the same.
ex- 101 101 101 101. How do I make it work?
ArrayList<String[]> coded = new ArrayList<String[]>();
Random rand = new Random();
for(int j=0; j<4;j++){
for (int i=0; i<3;i++){
rand1 = (rand.nextInt(4)+0)%2;
x1[i]= "" + rand1;
}
coded.add(x1);
}

You have only declared one x1 array (somewhere), so in essence you're just adding a bunch of references to the same array to the list. The array will contain the values that were inserted during the last iteration.
Declare the array inside the loop to fix the issue.
for (int j=0; j<4; j++){
String[] x1 = new String[3];
for (int i=0; i<3; i++){
rand1 = (rand.nextInt(4) + 0) % 2;
x1[i]= "" + rand1;
}
coded.add(x1);
}

Related

randomly select and delete 2 different items form array

How can I remove the item in an array that is selected by the random?.
Instead of giving me two different items in an array it's just printing the same item selected by the random.
String[] names = {"jey","abby","alyssa","cole","yzabel","miho"};
Random rand = new Random();
String names_rand = names[rand.nextInt(names.length)];
for(int i = 0; i < 2; i++){
System.out.println(names_rand);
}
It's simply because any code outside the for loop won't run again, try this to run the random code every loop to get a new (possible same since it's random) string from the array
String[] names = {"jey","abby","alyssa","cole","yzabel","miho"};
Random rand = new Random();
for(int i = 0; i < 2; i++){
String names_rand = names[rand.nextInt(names.length)];
System.out.println(names_rand);
}
as for deleting the item that would be somehow complicated using a string array as once it's allocated you can't add or delete from it (you can't modify it's size )unless you are willing to make a new temporary array, copy all of its items without the chosen string like this maybe :
String[] names = {"jey", "abby", "alyssa", "cole", "yzabel", "miho"};
Random rand = new Random();
for (int i = 0; i < Math.min(2, names.length); i++) {
int randInt = rand.nextInt(names.length), cpyIdx = 0;
String[] namesTemp = new String[names.length - 1];
for (int j = 0; j < names.length; j++) {
if (j != randInt) {
namesTemp[cpyIdx] = names[j];
cpyIdx++;
}
}
names = namesTemp;
a better version of this complicated code would be using an ArrayList, which allows to add and remove its items (change its size at runtime) easily with just one method call like this :
ArrayList<String> names = new ArrayList<>(Arrays.asList("jey", "abby", "alyssa", "cole", "yzabel", "miho"));
Random rand = new Random();
for (int i = 0; i < Math.min(2, names.size()); i++) {
int randInt = rand.nextInt(names.size());
names.remove(randInt);
}
you can read more about ArrayLists how to add/remove items through this link as well as many tutorials out there just write ArrayList java in google search engine
N.B : I've added Math.min(2, names.length) to the for loop condition as I was afraid you would get to the case that the array length would be less than the number of items you want to delete, using Math.min I'm ensuring that the for loop won't try access an item that isn't there in the array
If you are required to use Arrays then this way is probably among the best
with the limitations involved.
generate a random number and get the name
create a new temporary array to hold the all names less the one removed.
copy all names up to but excluding the one removed to the temp array
copy all names just after the one excluded to the temp array.
assign the temp array to the original array
normal exceptions will be thrown if a null or empty array is used.
Random r = new Random();
String[] names =
{ "jey", "abby", "alyssa", "cole", "yzabel", "miho" };
ArrayList<Integer> a;
int idx = r.nextInt(names.length);
String name = names[idx];
String[] temp = new String[names.length - 1];
for (int i = 0; i < idx; i++) {
temp[i] = names[i];
}
for (int i = idx; i < temp.length; i++) {
temp[i] = names[i + 1];
}
names = temp;
System.out.printf("'%s' was removed.%n",name);
System.out.println(Arrays.toString(names));
Prints something like
'jey' has been removed.
[abby, alyssa, cole, yzabel, miho]
It's interesting to note that the best way would be to use an ArrayList as already given in a previous answer. But the primary reason is that an ArrayList does not need to make a temporary array but simply copies in place. Then it adjusts the size value, effectively hiding the garbage still in the internal array.

How to retrivew elements of an Array of unkown size in android studio

I have created an app which will find the common factors of 2 or more numbers entered by the user. I have used a single Edit Text field to get user input. Different numbers are separated by comma (,). All the numbers are stored in an array.
My question is that how can I access the elements of the array of n size. Following is the code. I want to find the factors of all the user entered numbers. I can find the the factors of integernumbers[0] index but after that the code thorws ArrayIndexOutOfBoundsException.
int factors1 = 0;
int factors12 = 0;
StringBuilder sb = new StringBuilder();
String value = edtCommonFact.getText().toString()
String[] stringsNumber = value.split(",");
Integer[] integersNumbers = new Integer[stringsNumber.length];
for (int i = 0; i<stringsNumber.length; i++){
integersNumbers[i] = Integer.parseInt(stringsNumber[i]);
}
Arrays.sort(integersNumbers);
for (int i = 1; i<=integersNumbers[0]; i++){
if (integersNumbers[0]%i == 0){
factors1 = i;
sb.append(factors1).append(" ");
for (int j = 1; j<=integersNumbers.length; j++){
if (integersNumbers[j]%j == 0){
factors12 = j;
sb.append(factors12).append(" ");
}
}
}
}
String result = sb.toString();
commonFactResult.setText("Common factors are: " + result);
Thanks in Advance
You can use ArrayList because not like an array it doesn't need a size declaration. As an example if we wants an String array with size 10 we need to declare it as
String[] s = new String[10]
but in ArrayLists you can define the ArrayList and use it for any no of items.
List<String> s = new ArrayList<>()

How to store data in a string array using java collection

I have stored data in a List<String[]> and need to store those data into an another String array using a loop. I have created a String array (value) and stored data in there but the issue is first element is getting replaced by second inside the loop and it will show only the last element at the end of the loop.
CSVReader reader = new CSVReader(new FileReader(csvfile));
List<String[]> data = reader.readAll();
String[] values = new String[5];
for (int i = 1; i < 5; i++) {
values = data.get(i);
System.out.println(values[1]); // data is getting replaced here
}
System.out.println(values[1]); // this will show only the last stored value
Lists are 0 indexed so unless you intentionally want to skip the first element then don't start the loop iteration at 1 rather at 0.
Yes, when performing the last println after the loop only data related to the last String[] is shown because at each iteration you're updating values i.e. values = data.get(i); to store the current String[] hence the aforementioned outcome.
You probably want a String[][] as opposed to String[] because each String[] represents a line of the file.
Thus, assuming you only want to get the first five lines from data you can do it as:
String[][] lines = data.subList(0, 5).toArray(String[][]::new);
or for all the lines read:
String[][] lines = reader.readAll().toArray(String[][]::new);
and you can test it with:
System.out.println(Arrays.deepToString(lines));
// generating data
List<String[]> data =
Stream.iterate(0, n -> n + 1)
.limit(10)
.map(i -> new String[]{"a" + i, "b" + i, "c" + i, "d" + i, "e" + i, "f" + i})
.collect(Collectors.toList());
String[][] values = new String[data.size()][];
// copy the data
for (int i = 0; i < data.size(); i++)
{
values[i] = data.get(i).clone();
}
//print the result
Arrays.stream(values).map(Arrays::toString).forEach(System.out::println);
Replace :
for (int i = 1; i < 5; i++) {
values = data.get(i);
System.out.println(values[1]); // data is getting replaced here}
With:
for (int i = 0; i < 5; i++) {
values = data.get(i);
System.out.println(values[1]); // data is getting replaced here}
I think you have a little error inside the for loop. Try this:
CSVReader reader = new CSVReader(new FileReader(csvfile));
List<String[]> data = reader.readAll();
String[] values = new String[5];
for (int i = 1; i < 5; i++) {
values[i] = data.get(i);
System.out.println(values[1]); // data is getting replaced here
}
System.out.println(values[1]); // this will show only the last stored value
I think you are missing the "[i]" at the first line inside the for loop.
Your data variable contains a list of String[] (string arrays). Your for loop is attempting to store them in values which is a single String[].
Depending on what you are trying to do, you can do as the comments suggest and make a 2D String array. However, the fact that you want to remove them from a perfectly good list of String[]'s leads me to believe you probably want them in one big String[].
Below is an example of how to put the first N (in this case 5) words you parse from the csv into the values variable. However, we would be able to give you better guidance if you provided what the ultimate use case of your code snippet is.
// initialize test data
List<String[]> data = new ArrayList<String[]>();
String[] a = {"a1", "a2"};
String[] b = {"b1", "b2"};
String[] c = {"c1", "c2"};
data.add(a);
data.add(b);
data.add(c);
// big N is how many words you want
int N = 5;
// little n tracks how many words have been collected
int n = 0;
String[] values = new String[N];
// loop through csv collect
for (int i = 0; i < data.size(); i++){
String[] cur = data.get(i);
// loop through the strings in each list entry
for (int j = 0; j < cur.length; j++){
// store value and increment counter
values[n] = cur[j];
n++;
// stop if maximum words have been reached
if (n >= N)
break;
}
// stop if maximum words have been reached
if (n >= N)
break;
}
for (int i = 0; i < values.length; i++)
System.out.println(values[i]);

Find the maximum of the length of 2 arrays

I am passing 2 arrays to the controller with different lengths, I want to execute a for loop and length of that will be the max of the length of 2 arrays.
I am not getting how to execute that. I tried Math.max but its giving me error as cannot assign a value to the final variable length.
String[] x =0;
x.length = Math.max(y.length,z.length);
for(int i=0; i < x.length; i++)
The no of elements in x and y are not fixed. it changes what we are passing from the front end.
Initialize the new array with the desired length:
String[] x = new String[Math.max(y.length,z.length)];
In case you don't need to create an array, just use the result of Math.max as conditional to stop your loop:
for (int i = 0; i < Math.max(y.length,z.length); i++) {
//...
}
Just bring your Math.max() operation into the array's initialization.
String[] x = new String[Math.max(y.length, z.length)];
Here's an expansion for clarity:
int xLength = Math.max(y.length, z.length);
String[] x = new String[xLength];
Edit: Unless, OP, you're not interested in creating another array...
I want to execute a for loop and length of that will be the max of the length of 2 arrays
Just bring your Math.max() operation into your for loop:
for(int i=0; i < Math.max(y.length, z.length); i++){
//code here
}
Set a variable to the maximum length of the arrays, create a new array with that length and then loop until that point.
int maxLen = Math.max(y.length, x.length);
String[] array = new String[maxLen];
for(int i = 0; i < maxLen; i++){
// Loop code here
}
int max_length = Math.max(y.length,z.length);
for(int i=0; i < max_length ; i++){
//...
}
you can use that max_length to create a new String[] if you are trying to create an array with total length of y and z arrays, like
String[] newArray = new String[max_length];

Arrays in array, 100 rows, dynamic columns

I'm trying to get this:
arrays[1][0] = 5
arrays[2][0] = 7
arrays[2][1] = 2
arrays[3][0] = 6
arrays[3][1] = 9
arrays[3][2] = 11
So I want arrays[1][] to have one element of random data, arrays[2][] to have 2 elements of random data and so on until I have 100 arrays. So my last array would be arrays[100][] with 100 elements of random data.
This is the code I have now but I get a NullPointerException when arrays[i][j] = generator.nextInt(max) is executed:
Comparable[][] arrays = new Comparable[100][];
for (int i=1; i<101;i++){
for (int j=0; j <= i-1; j++){
arrays[i][j] = generator.nextInt(max);
}
}
Your
Comparable[][] arrays = new Comparable[100][];
line only creates the outermost array. You need to create the arrays that go in it, e.g. something like this:
Comparable[][] arrays = new Comparable[100][];
for (int i=1; i<101;i++){
arrays[i] = new Comparable[/* relevant length here*/]; // <====
for (int j=0; j <= i-1; j++){
arrays[i][j] = generator.nextInt(max);
}
}
It's unclear to me why you start i at 1 or where the randomness should be (I'm guessing at /* relevant length here */), but hopefully that points you the right way.

Categories