+ 1
Making a array and while loop
Hello friends, I have a homework but I don’t know from where should I start I have to write a program In java that must have the following concept First I have to make an array that has 4 int index And after that I have to make a while loop When I run the program the index must change their place with each other I hope that I explain it well Thanks in advance 🤗🤗🤗
12 Respostas
+ 12
Plz elabrate your qustion
I think you want to shuffel your int indexs.
+ 12
Sam
I think this you want run that programme
int arr[] = {1,2,3,4,5};
Random r = new Random();
int random;
for(int i=0;i<arr.length;i++)
{
random = r.nextInt(i+1);
int temp = arr[i];
arr[i] = arr[random];
arr[random]=temp;
}
for(int i:arr)
{
System.out.print(i+", ");
}
+ 12
Sam
// first line of you programme
import java.util.*;
And inside the class paste it that code that i wrote.
Than your programme work properly.
+ 5
create an array:
int[] arr = new int[4];
arr is an empty array (all 4 elemnts are 0).
index from 0 to 3 (in java an index starts always at 0).
how to fill:
e.g. arr[0] = 4; //the first element is 4
arr[2] = 1; //third element is 2
Or:
int[] arr = {1,2,3,4};
This would be a filled array.
int i = 0;
while(i < arr.length){
System.out.println(arr[i]);
i++; //increment i
}
+ 5
Sam Sorry I didn't see that you want to shuffle the array.
In a special order or randomly?
+ 5
If you are not familiar with Random() you can do this:
int[] arr = {1,2,3,4};
int i = 0;
while(i < arr.length / 2){
int temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
i++;
}
This code will reverse the array. You can play around with the index to see what happens.
+ 5
Sam
Add another for loop to print the values.
+ 3
thank u Sumit Programmer😎😎 now it works
+ 2
Sumit Programmer😎😎 dear the program which you have wrote it has error can you check it once 🙏🏿🙏🏿🙏🏿🙏🏿
+ 2
Denise Roßberg when i run your program
the result is
no output
+ 1
Sumit Programmer😎😎 yes exactly
+ 1
Denise Roßberg sorry but it’s not changing their place with each other