+ 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 🤗🤗🤗

16th Jun 2019, 5:04 PM
Sam
Sam - avatar
12 Answers
+ 12
Plz elabrate your qustion I think you want to shuffel your int indexs.
16th Jun 2019, 5:43 PM
Sumit Programmer😎😎
Sumit Programmer😎😎 - avatar
+ 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+", "); }
16th Jun 2019, 6:01 PM
Sumit Programmer😎😎
Sumit Programmer😎😎 - avatar
+ 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.
17th Jun 2019, 4:57 AM
Sumit Programmer😎😎
Sumit Programmer😎😎 - avatar
+ 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 }
16th Jun 2019, 5:45 PM
Denise Roßberg
Denise Roßberg - avatar
+ 5
Sam Sorry I didn't see that you want to shuffle the array. In a special order or randomly?
16th Jun 2019, 6:08 PM
Denise Roßberg
Denise Roßberg - avatar
+ 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.
16th Jun 2019, 6:24 PM
Denise Roßberg
Denise Roßberg - avatar
+ 5
Sam Add another for loop to print the values.
17th Jun 2019, 8:52 PM
Denise Roßberg
Denise Roßberg - avatar
+ 3
thank u Sumit Programmer😎😎 now it works
17th Jun 2019, 5:21 AM
Sam
Sam - avatar
+ 2
Sumit Programmer😎😎 dear the program which you have wrote it has error can you check it once 🙏🏿🙏🏿🙏🏿🙏🏿
17th Jun 2019, 1:42 AM
Sam
Sam - avatar
+ 2
Denise Roßberg when i run your program the result is no output
17th Jun 2019, 1:43 AM
Sam
Sam - avatar
16th Jun 2019, 5:45 PM
Sam
Sam - avatar
+ 1
Denise Roßberg sorry but it’s not changing their place with each other
16th Jun 2019, 5:51 PM
Sam
Sam - avatar