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.
Related
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<>()
I'm working on a custom ArrayList implementation and I have one method where I'm trying to remove an item per conditions from an array such as E[] elements. The array is initialized by doing something like this:
String[] contents = {"chicken", "hippo", "goat"};
ArrayI<String> newarray = new ArrayI(contents);
newarray.chooser(new LongChooser());
It should remove words length 4 or less and return an array like this:
["chicken", "hippo"]
I'm trying not to use any built in methods, like remove(), clone(), arraycopy(), etc. I can't seem to get this to work, I've tried creating a duplicate array and trying to copy elements over like this:
E[] copy = (E[]) (new Object[this.size-1]);
for (int i = 0; i < size; i++) {
if (shorter) {
copy[i] = elements[i];
}
else {
for (int j = i; j<this.size-1; j++) {
elements[j] = elements[j+1];
}
elements[size-1] = null;
size -= 1;
}
for (int i =0; i< copy.length; i++) {
elements[i] = copy[i];
}
size -= 1;
I know this is not the correct way because they aren't the same size array and just returns [longword, longerword, null]. Also I'm pretty sure I should be using the size variable, but it doesn't seem to do much.
How do I get this to work? Thanks.
Create an array to hold the [filtered] results. Its initial size is zero.
Iterate through contents.
If the current element of contents needs to be retained, then
create a temporary array whose length is one greater than the array that holds the results.
copy the results array to the temporary array
set the last element of the temporary array to the current element of contents
assign the temporary array to the results array
Here is the code, using only simple arrays. I presume you can adapt it to your needs. Note that the last line is simply to check the value of newContents. It is not required.
String[] contents = {"chicken", "hippo", "goat"};
String[] newContents = new String[0];
for (String str : contents) {
if (str.length() > 4) {
String[] temp = new String[newContents.length + 1];
for (int i = 0; i < newContents.length; i++) {
temp[i] = newContents[i];
}
temp[newContents.length] = str;
newContents = temp;
}
}
System.out.println(Arrays.toString(newContents));
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);
}
I already have one Array with random numbers between 0-999.
I also have created two new arrays, one with correct the size to hold all numbers 0-499, and one with the correct size for numbers 500-999.
Problem is to then loop through the Array holding all numbers and copying the right numbers 0-499 and 500-999 to the new Arrays.
Anyone know the correct way to do this? Have spent many days now trying to figure this out.
What i got so far:
public static void main(String[] args) {
Scanner scannerObject = new Scanner(System.in);
Random generator = new Random();
System.out.print("How many numbers between 0 - 999?" );
int number= scannerObject.nextInt();
int [] total= new int[number];
for(int index = 0; index < total.length; index++ )
{
total[index] = generator.nextInt(1000);
}
System.out.println("Here are the random numbers:");
for(int index = 0; index < total.length; index++ )
{
System.out.print(total[index]+ " ");
}
int lowNumber=0;
int largeNumber = 0;
for(int index = 0; index < total.length; index++ )
{
if (total[index] < 500)
{
lowNumber++;
}
if (total[index] >= 500)
{
largeNumber++;
}
}
System.out.println();
System.out.println(lowNumber);
System.out.println(largeNumber);
int [] totalLownumber = new int [lowNumber];
int [] totalLargeNumber = new int [largeNumber];
for(int index = 0; index < total.length; index++ )
{ // TODO
}
}
2 of the approaches you can take are as follows:
You can go through the initial array, count the elements you have, and use the counter values to define the size of the arrays you need. You then go over the original array once again and copy the elements to their respective array. You can use the counter values once again (you would need to reset them first) to allow you to keep track in which array location will the current number need to go. This should be similar to what you are doing.
Consider using a variable length data structure such as a List (ArrayList in Java). This would allow you to go over your original array and assign the numbers to their respective list (let's call them largeNumberList and lowNumberList). Since these collections have a dynamic size, you would only need to traverse the array once and assign as you go along.
The latter approach is usually what is used more often, however, since it would seem that this question is related to homework, I would recommend you try both approaches and compare them.
Try this:
int lowIndex = 0;
int largeIndex = 0;
for(int index = 0; index < total.length; index++ ) {
if (total[index] < 500) {
totalLowNumber[lowIndex++] = total[index];
} else {
totalLargeNumber[largeIndex++] = total[index];
}
So, I have a method like this
public String[][] getArgs(){
And, I want it to get results out of a for loop:
for(int i = 0; i < length; i++){
But how do I append them to the array instead of just returning them?
Create a String[][] array inside your method, fill this array inside a loop (or in any other way) and return that array in the end.
If you are sure you want to have only one for loop (instead of two, typical for 2-dimensional array), ensure your loop will go through the number of examples equal to the number of fields in your String[][] array. Then you can calculate the double-dimension array indexes from your single loop-iterator, for example:
for(int i = 0; i < length; i++){
int a = i % numberOfCollumnsInOutput;
int b = i / numberOfCollumnsInOutput;
String[a][b] = sourceForYourData[i];
}
(Of course which array dimension you treat as collumns (and which to be rows) depends on yourself only.) However, it is much more typical to go through an n-dimensional array using n nested loops, like this (example for 2d array, like the one you want to output):
for(int i = 0; i < dimensionOne; i++){
for(int j = 0; j < dimensionTwo; j++){
array[i][j] = someData;
}
}
For your interest. A sample code according to Byakuya.
public String[][] getArgs(){
int row = 3;
int column =4;
String [][] args = new String[row][column];
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
args[i][j] = "*";
return args;
}
You can make a LinkedList from that array, and then append the elements to it, and then create a new array from it. If you are not sure i'll post some code.