Android Random Number - java

I m generating one random card from array. and assigning it.'
Below is the code..but its is showing an error.
What is the problem?
public void rand() {
String rank[]= {"tclub1.png", "tclub2.png", "tclub3.png", "tclub4.png", "tclub5.png", "tclub6.png", "tclub7.png", "tclub8.png", "tclub9.png", "tclub10.png","tclub11.png", "tclub12.png", "tclub13.png"};
Random randInt = new Random();
int b = randInt.nextInt((rank.length));
showcard1.setBackgroundResource(b);
}

b is an int
so you need rank[b] the array at some point in your code
According to your code maybe it should read
showcard1.setBackgroundResource(rank[b]);

Try changing to int b = randInt.nextInt((rank.length)) - 1; (because rank.length = 13 and your array is indexed from 0 to 12)

Related

Tried to make a variable that's a random number but got an error. Can anyone tell me what's wrong?

I want to create a random int value ranging from 1-3. I researched and wrote this:
#Override
Random rand = new Random();
n = rand.nextInt(3) + 1;
public int quantityDropped(Random par1Random) {
return n;
}
So it said my code had errors and it didn't specify. I can't find the error myself, can anyone help me?
As per the documentation, it says that the Random.nextInt method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)".
To get a random number between min (inclusive) and max (inclusive) in Java, you do this:
Random r = new Random():
int randomNum = random.nextInt(max - min + 1) + min;
As such, to get a random number from 1-3 (both inclusive), do this:
Random r = new Random():
int randomNum = random.nextInt(3) + 1;
In javascript you can use:
parseInt(Math.random() * 4)
Your method declaration syntax is incorrect.
At the simplest, the method could look like this:
public int quantityDropped() {
return ThreadLocalRandom.current().nextInt(1, 4);
}
ThreadLocalRandom extends Random with some helpful methods, like generating an int in a (half-open) range.
If quantityDropped() is intended to override a method of a parent class, or implement an abstract method declaration in a parent type, you should add the #Override annotation.
If you intended to pass a random number generator to the method for some reason (for example, you want to explicitly seed the generator to produce a consistent sequence for testing), the method could look like this:
public int quantityDropped(Random random) {
return random.nextInt(2) + 1;
}
Again, add the #Override annotation if appropriate.
However, I doubt that's a good design for a class. If you are trying to create a mock implementation of some type that uses random numbers to imitate a real component, consider storing the Random instance in a field of that object:
class MockQuantityDropper implements QuantityDropper {
private final Random random;
MockQuantityDropper(Random random) { this.random = Objects.requireNonNull(random); }
#Override
public int quantityDropped() {
return random.nextInt(3) + 1;
}
}

exclude number from the Random picker list

i have a Random picker code that picks random number for ex from 1 to 6 ..
can u give me a method how to exclude the picked number from the list of random pick ..
import java.util.Random;
Random rand = new Random();
int n = rand.nextInt(6) + 1;
like that for ex :
1.2.3.4.5.6
random pick=5
1.2.3.4.6
random pick=2
1.3.4.6
.. etc
ty in advance guys
You can add the numbers that have already been picked to an ArrayList and pick a number until the number is not contained in the list.
// list of numbers that I already picked
ArrayList<Integer> randomNumbersPicked = new ArrayList<>();
// int to save the current random number
int myCurrentRandomNumber;
while(iNeedAnotherNumber){
do {
myCurrentRandomNumber = generateRandomNumber(a, b);
//repeat this until the number is not in the list
} while (randomNumbersPicked.contains(new Integer(myCurrentRandomNumber)));
//here there is a unique random number, do what you will
System.out.println("A new number has been picked: " + myCurrentRandomNumber);
//add the number to the list so it wont be picked again
randomNumbersPicked.add(new Integer(myCurrentRandomNumber));
}
Best Regards!
Dknacht.
Put all valid numbers into an ArrayList and instead select a random index from the list. Then remove that number from the list and repeat.
My Java is a little rusty, so hopefully the code I write makes sense:
ArrayList<int> validOptions = /**/; // make your list with all initial options
int firstIndex = random.Next(validOptions.count());
int firstPick = validOptions.get(firstIndex);
validOptions.removeAt(firstIndex);
int secondIndex = random.Next(validOptions.count());
int secondPick = validOptions.get(secondIndex);
validOptions.removeAt(firstIndex);

java array from newboston lesson

While going over newboston java tutorial, I am looking at array lessons and wondering why assigning variable in array is ++freq[1+rand.nextInt(6)]. I understand the 1+rand.nextInt(6) part but ++freq, I do not.
Because I come from other script background, I would think freq[roll] = 1+rand.nextInt(6) is the right way(but clearly not right).. can someone explain to me why ++freq[1+rand.nextInt(6)] works here?
Another words,
Aren't I doing
freq[0] = 1+rand.nextInt(6);
freq[1] = 1+rand.nextInt(6);
freq[2] = 1+rand.nextInt(6);
------ continue till
freq[9] = 1+rand.nextInt(6);
??
class apples {
public static void main(String[] args) {
Random rand = new Random();
int freq[] = new int[7];
for ( int roll=1; roll < 10; roll++) {
//++freq[1+rand.nextInt(6)];
freq[roll] = 1+rand.nextInt(6);
}
It's for the increment of value of freq array positioned at the 1+rand.nextInt(6) index. What you're doing is assigning value 1+rand.nextInt(6) to freq[roll]. So you are replacing the value at the position not incrementing it.

How to get unique random int?

static int n = -1;
private static int repeatBuffer[] = new int[10];
static {
repeatBuffer[0] = 0;
//and more
repeatBuffer[9] = 9;
}
static public void randomize() {
do {
Random r = new Random();
randomNumber = r.nextInt(20);
} while (!uniqueInt(randomNumber));
Log.e(TAG, "" + randomNumber); //here I need have a unique int
}
private static Boolean uniqueInt(int random) {
for (int i = 0; i < 9; i++) {
if (random == repeatBuffer[i]) {
return false;
}
}
if (++n > 9)
n = 0;
repeatBuffer[n] = random;
return true;
}
Sometimes I'm getting same int twice, I'm wondering where is the problem? And is it even work? I spend quite a lot of time on this, and I give up. I think I need some minor tweaks in code :)
An easier way to get a random int is to create a List of integers List<Integer>, adding it with numbers that you would like to have. Then shuffling the List using Collections.shuffle(list);. Now start reading from the beginning of the list and you will get a unique random int each time.
Just make sure that each time you "read" a number from the list, either remove it from the list or increase the index for where you read.
That's the normal behavior of a random number generator, it's correct to generate repeated numbers as long as the number distribution remains uniform.
If you need a set of unique random numbers, you can generate them inside a loop and ask at every iteration if the newly generated number is present in the set of generated numbers. If not, add it, if yes, keep iterating - until the set has the desired size.
Er, a unique random between 1 and 20? What happens when it runs the 21st time?
Try making a List of the Integers between 1 and 20. Use Collections.shuffle() to shuffle the list. Then pop the first item off the front of the list and use that.

Generating an array of random points in java with no duplicates

I am fairly new to Java, and I want to generate an array of random (x,y) coordinates of length 'number' that contains no duplicates. x or y values can be repeated, but there must be no repeated (x,y) coordinates. The output does not have to be Points, simply some way of holding x,y values for coordinates.
I can generate an array of random points, and have tried using a Set to ensure there are no duplicate values, but have run into problems. I tried using the condition "while (set.size)" and the 'add' method which should disallow duplicates, to create an output of the correct size which contains unique points.
This is the code:
Set<Point> set = new HashSet<Point>();
Random position = new Random();
Point test=new Point();
do{
test.x=position.nextInt(xx);
test.y=position.nextInt(yy);
//xx and yy are the random number limits called from another part of the code
set.add(test);
}
while (set.size()<number);
List<Object> list = new ArrayList<Object>(set);
Object[] coord = list.toArray();
This outputs an array of the correct length, but every element is the same. Can anyone offer any help?
Thanks
test points to the same variable in space everytime you loop, to fix that create a new instance inside the loop - not just once before it:
Set<Point> set = new HashSet<Point>();
Random position = new Random();
Point test;
do{
test = new Point();
test.x=position.nextInt(xx);
test.y=position.nextInt(yy);
//xx and yy are the random number limits called from another part of the code
set.add(test);
}
while (set.size()<number);
List<Object> list = new ArrayList<Object>(set);
Object[] coord = list.toArray();
You are modifying the same point object. However, since you change X and Y every time, you also changing hash code and equality of the point, so you end up placing the same object multiple times in the set. Interesting case.
try
do{
test = new Point();
test.x=position.nextInt(xx);
test.y=position.nextInt(yy);
//xx and yy are the random number limits called from another part of the code
set.add(test);
}
while (set.size()<number);
Value select Randomly but not repeated
Random rndm = new Random();
String[] selectedNumber = new String[15];
String[] sequanceNumber = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"};
//*****FIRST LOOP START*****//
for(byte a = 0; a < 15;){
int temp = rndm.nextInt(15)+1;
//*****SECOND LOOP START*****//
for(byte b = 0; b < 15; b++){
String s4 = temp+"";
//*****CHECKING CONDITION START*****//
if(s4.equals(sequanceNumber[b]) ){
selectedNumber[a] = s4;
String s1 = sequanceNumber[b];
s1 = s1.replace(s1, " ");
sequanceNumber[b] = s1;
a++;
}
//*****CHECKING CONDITION END*****//
}
//*****SECOND LOOP END*****//
}
//*****FIRST LOOP END*****//
//*****PRINT ALL RANDOM VALUES BUT NOT REPEATED VALUES*****//
System.out.println(Arrays.toString(selectedNumber));

Categories