This question already has answers here:
How do I declare and initialize an array in Java?
(31 answers)
Closed 8 years ago.
I need to create a list of available television channels (identified by integers). I am thinking that I would begin by creating int [] list = 5,9,12,19,64. Here is the code:
public NotVeryGoodTV(int[] channels) {
int [] list =5,9,12,19,64;
but I am getting a syntax error stating that a { is needed after "=". I would like to have a list of tv channels that would be available to the user once they turned on their television.
This is syntactically correct (instead of your array declaration):
int[] list = {5, 9, 12, 19, 64};
But it is not random, if you want to create an array with random integers:
Random randGen = new Random(); //random generator: import java.util.Random;
int maxChanNumber=64; //upper bound of channel numbers (inclusive)
int minChanNumber=1; //lower bound of channel numbers (inclusive)
int amountOfChans=5; //number of channels
int[] list = new int[amountOfChans]; //create an array of the right size
for (int k=0;k<amountOfChans;k++) //populate array
list[k]=minChanNumber+randGen.nextInt(maxChanNumber-minChanNumber+1);
Actually this codes does NOT check if you generate a different channel number (integer) for every item of the array: it is possible that in the array you will find two or more times the same number, but it is not difficult to adapt the code to avoid this, anyway the direction to take to have really random channel numbers is this one.
Replace:
int [] list =5,9,12,19,64;
With:
int[] list = { 5,9,12,19,64 };
The brackets tell Java that you are declaring a list.
However the numbers are not random; they are the ssame every time.
replace line 2:
int [] list =5,9,12,19,64;
with this code:
int[] list = {5,9,12,19,64};
Yep, you need to encase the list in curly braces like this:
int [] list = {5, 9, 12, 19, 64};
Just proper Java syntax issues.
Related
I am trying to create three different random numbers from 0-3 and assign each to an int variable. How do I do this? Also, the array will not generate when .opset is (0, 2) but it will when it is (1, 3). How can I fix this?
package varselect;
import java.util.Arrays;
import java.util.Random;
public class varselect {
public static void main(String[] args) {
final int[] ints = new Random().opset(0, 2).distinct().limit(3).toArray();
}
}
There is no method named opset in class java.util.Random, so the code in your question does not compile. You can use the method ints instead:
final int[] ints = new Random().ints(0, 4).distinct().limit(3).toArray();
System.out.println(Arrays.toString(ints));
Note that ints takes the lower bound (inclusive) and upper bound (exclusive) of the range in which you want to generate numbers, so if you want numbers between 0 and 3 inclusive then you need to specify (0, 4) as the arguments.
This would be the correct way to do it:
final int[] ints = new Random().ints(0, 4).distinct().limit(3).toArray();
It uses ints(0, 4) which provides an IntStream with values from 0-3, we then call .distinct() to get distinct values, limit(3) to get 3 distinct values and lastly we turn it into an array.
If you want your result random integer array of length array 3 then you should pass bound parameter as 3 to Random.ints(int randomNumberOrigin, int randomNumberBound).
int[] randomIntArray = new Random().ints(0, 4).distinct().limit(3).toArray();
For example int new [] {1, 2, 3, 4, 5, 6, 7, 8}, I'd like to take 4 of them randomly then insert them to another array for later use.
Dumb question, but does this also need generators? The elements are already there so I don't see any use for generators here...
Below snippet should do the trick:
private static final Random RANDOM = new Random();
public int[] getRandom4( int[] input ){
final int[] output = new int[4];
for( int i = 0; i < 4; i++ ){
output[i] = input[RANDOM.nextInt(input.length)];
}
return output;
}
Note: I prefer the Random instance to be static, but if you dislike that. Then just move it inside the method
You can but the elements inside ArrayList instead of simple array
and then shuffle the elements usingCollections.shuffle(list)
and then take first three or four elements or whatever you wants.
This question already has answers here:
How can I generate a list or array of sequential integers in Java?
(9 answers)
Closed 5 years ago.
I am relatively new to Java programming and am trying to create an array with values from (2017 - 3017).
I was wondering if there is a way to create an array and have it pre-filled with these values so instead of doing:
int[] anArray = {2017, 2018, 2019, 2020... 3017}
which seems extremely long-winded, I can simply define a range of integers I wish to add to the array.
I know there are similar question to this one on the site, however none of them have answers that help me.
Thanks!
Edit: I forgot to mention I am using Java 7 and therefore cannot use IntStream.
How about this:
int[] anArray = IntStream.rangeClosed(2017, 3017).toArray(); //closed includes upper bound
Java 7 would simply require a loop to fill the array:
int min = 2017, max = 3017;
int count = max - min + 1; //we're including upper bound
int[] anArray = new int[count];
for (int i = 0; i < count; i++, min++) {
anArray[i] = min; //reused and incremented min
}
Well it is answered. But just to point out another way in java .. you can count the number of integers that will be coming and use iterator to fill the array.Let me know if you have any doubts in this In short I am saying to do like the following:
int arr[] = new int[1001];
for(int i=2017;i<=3017;i++){
arr[i-2017]=i;
}
This question already has an answer here:
Select a random value from an Array
(1 answer)
Closed 8 years ago.
I'm writing a program that generates co-primes of a number.
Now for example a number 'A' has 50 co-primes, my objective is to randomly select a co-prime from the list of all co-primes generated for the number A.
Again for example:
consider a number 15, it has co-primes - {1, 2, 4, 7, 8, 10, 11, 13, 14}. So now i have to select randomly from these values. Likewise, if i generate an array of any values, then how to randomly select from this array.
So in general my question is how to generate a random number from the array of numbers that i have. Now, those numbers in the array can be anything. Like not necessarily natural numbers, or prime numbers, etc.
So is there any java function to do so. I've burnt my brain searching the internet, but didn't find one. I usually go for finding result on google, rather than asking quetions on forums. But when one gets exhausted, it's better to ask experts out there who might have faced similar problems.
Thanks in advanced!!
Is that what you want ?
int[] arr = { 1,5,9,3,2,7 };
Random rd = new Random();
int dice = arr[rd.nextInt(arr.length)];
You can use the java.util.Random class for this:
public int chooseRandom(int[] coPrimes) {
//Creates the Random instance
Random randomizer = new Random();
//Generate a random integer between 0 and the length of the array (exclusive)
int value = randomizer.nextInt(coPrimes.length);
//Return the element at that generated index
return coPrimes[value];
}
I have looked at Randomize or shuffle an array Randomize or shuffle an array
I am not sure if this is the best approach to make.
I want to randomize the indices of an array with 3 items.
12
4
5
int numbers[] = new int[3];
I tried using the Maths.Random
int randomoption2 = opmin + (int)(Math.random() * ((opmax - opmin) + 1));
but I then have an issue with repetition of the indices values. What is the best approach to randomize the indices so there is no repetition .
eg
a[1] = 2;
I don't want two elements in the array coming back with an indices of one
http://www.exampledepot.com/egs/java.util/coll_Shuffle.html
public class randomorder {
public static void main(String [] args)
{
randomorder();
System.out.println(randomorder());
}
public static ArrayList randomorder(){
ArrayList nums = new ArrayList();
nums.add(1);
nums.add(2);
nums.add(3);
Collections.shuffle(nums);
return nums;
}
}
I now need to store each of the numbers in variables so they can be outputted
System.out.println(options[0]);
Use Collections.shuffle:
Integer[] numbers = { 1, 2, 3, 4, 5 };
Collections.shuffle(Arrays.asList(numbers));
See it working online: ideone
It uses the Fisher-Yates shuffle internally. This is an efficient shuffling algorithm that won't give you duplicates.
Related
Java's Collections.shuffle is doing what?
How to convert int[] to Integer[] in Java?
Arrays.asList() not working as it should?
Just keep three booleans through an array of booleans. Once you hit 0, 1, or 2 index set them to true.
Choose a random position and do while(boolean[number chosen] == true) redo your random choice.