Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to generate a random double for this section of my assignment.
The question is
"Each week, each female Guppy who is 10 weeks old or older has a 25 percent chance of spawning".
I would like to generate a random double to determine if each female Guppy should spawn or not.
My code so far:
Random r = new Random();
if (isFemale == true && getAgeInWeeks() >= 10) {
//?
}
I don't see any reason to generate a random double according to your question. What you need is an integer ranging from 0 to 3 inclusive where each number account for 25% for the spawning.
Random r = new Random();
if (isFemale == true && getAgeInWeeks() >= 10) {
// Generate a random integer in [0,3]
// Since there is a 25% or 1/4 chance
if(Math.abs(r.nextInt()) % 4 == 1){
//Note that the 1 in the condition can be replaced by any
// integer in [0,3]
//Put spawning code here
}
}
Check out this link for more information on random:
Random (Java Platform SE 7
To generate a random double, you can look at this question, however, this problem can more easily be solved by generating random ints.
In your situation, generating an int between 0 to 3 is what you want because checking if it is 0 will be true 25% of the time (1 Value / 4 Possible values = 25%).
EDIT: If you would like to also generate a random number to see how many spawn a Guppy will have use threadLocalRandomInstance.nextInt(int bound); like before.
These constraints can be translated to code like this:
import java.util.concurrent.ThreadLocalRandom;
public class Test {
public static void main(String[] args) {
ThreadLocalRandom tlr = ThreadLocalRandom.current();
int num = tlr.nextInt(3 + 1); //Bound is exclusive so add 1.
int spawn;
if(num == 0) {
spawn = tlr.nextInt(100 + 1); //Again, bound is exclusive so add 1.
} else spawn = 0;
System.out.println("This guppy had " + spawn + " spawn.");
}
}
I use ThreadLocalRandom as it is more straightforward as supported by this answer.
If you are not using Java 1.7+, use Random#nextInt(int) instead as also shown by that answer.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I want to write a recursive method that fills and returns a String[] list of random balls for either "blue" or "red" of length n where n is a random odd number.
I wrote this method to generate an odd number in range 1-10 to use as a parameter for the recursive method.
public int ranNum (int ranN) {
int min = 1
int max = 10
Random r = new Random();
ranN = min + r.nextInt((max - min)/2)*2;
return ranN;
}
Is the (random odd number) method right? How to implement the recursive method?
A recursive function is a function which calls itself directly or via any amount of intermediate function calls.
The first step usually is to think about the termination. In your case you want to either count from 1 up to n or from n down to 1. And when the function terminates you have the choice of either returning the final value (it's called tail-recursion) or start building up your answer by traversing the call stack upwards. The later is being used, when you have one long calculation and you just want the last value (e.g. Fibonacci-Numbers).
And then do the work in every step:
String[] tailRecursion(int n, String[] accumulator, Random rnd)
{
if(n == 0) {
return accumulator;
}
accumulator[n-1] = rnd.nextBoolean() ? "red" : "blue";
return tailRecursion(n-1, accumulator, rnd);
}
The method is called via tailRecursion(10, new String[10], new Random())
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have the following class:
public class CardGenerator {
private static final Random random = new Random();
private CardGenerator() {
}
public static long generateNumber() {
int identifier = random.nextInt(1_000_000_000 - 100_000_000 + 1)
+ 100_000_000; //9 digits
long number = 400_000 * 1_000_000_000L
+ identifier; //15 digits
int checksum = Luhn.getChecksum(number);
number = number * 10 + checksum; //16 digits
return number;
}
public static int generatePIN() {
return random.nextInt(10_000 - 1_000 + 1) + 1_000; //4 digits
}
}
or is it better practice to create a new Random object in every method?
"Better" always depends on your exact requirements.
The things to consider:
do you want your code to be testable (the above is only to a certain degree)
do you want your code to work in a multi threaded environment, and should the different threads see the same random numbers
In other words, the distinct non-answer: you have to understand the contract that your code will be used for. Then you can decide what is appropriate.
The above is probably okay on a "throw away after single exercise" level, but not more.
You might be thinking, that generating a new Random object might create numbers more, eh, randomly. But this is not the case. Calling next() always changes the seed used to create random numbers.
protected int next(int bits) { // is called by nextInt()
long oldseed, nextseed;
AtomicLong seed = this.seed;
do {
oldseed = seed.get();
nextseed = (oldseed * multiplier + addend) & mask;
} while (!seed.compareAndSet(oldseed, nextseed));
return (int)(nextseed >>> (48 - bits));
}
So you have no advantages in creating a new Random object each time but you have a bit less performance because you are always creating a new object.
So yes, it's totally okay to stick with one Random object.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
The following Java code segment is supposed to print, as a double, the mean average of a sequence of non-negative integers entered by the user. A negative input signals the end of the sequence (it is not itself part of the sequence). However, the code is not working. I am supposed to find 4 logic errors within this segment. Please help me find the 4 logic errors?? I know one is its integer division.
public class practice
{
public static void main (String[]args)
{
int sum = 0;
int numVals = 0;
Scanner scan = new Scanner(System.in);
System.out.println(("enter next integer (-ve to stop): "));
int i = scan.nextInt();
while (i > 0)
{
sum = sum + i;
numVals = numVals + 1;
}
System.out.println("average = " + sum / numVals);
}
}
I won't give you full solution, however, it'll be helpful if you pay attention to:
int division as you said,
does your loop terminate? Is someone changing i? Hint: No, and
how do you ask for input? Do you see any loops there? Why it's asking you for only one input?
Not an error, but pay attention to Java Naming Conventions, class name should begin with upper case
Since the homework is for logic errors, I could point out other errors.
the class name should start with upper case letter.
the println doesn't need two nested parenthesis.
the sum should be a long rather than an int to avoid overflows.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
So I started the Euler Project and the first problem was very easy, however I cannot get the answer because the program I created is not running. It compiles fine but when I run it, it never runs. Project Euler says that the problems " with efficient implementation will allow a solution to be obtained on a modestly powered computer in less than one minute." Which leads to my question. Am i stuck in an infinite loop or does my computer not have the power to run my program?
The problem is: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
public class Euler1
{
public static void main(String[] args)
{
double x = 1;
int count = 0;
int total = 0;
while( x < 1000)
{
if((x/3 == (int)x) || (x/5 == (int)x))
{
count++;
x++;
total += x;
}
}
System.out.println(total);
}
}
Your program is wrong.
while( x < 1000)
{
if((x/3 == (int)x) || (x/5 == (int)x))
{
count++;
x++;
total += x;
}
}
Notice that x is only incremented if the condition is true. x starts at 1, so the condition is not true, so x never gets incremented and stays at 1.
Also, x/3 == (int)x and x/5 == (int)x are not correct tests for divisibility. Neither of them are ever true unless x is 0.
The problem is that if your if condition is false in the while loop, x never gets incremented...
(and it will always be false unless x is 0)
You are getting stuck in an infinite loop. Your if-statement is never being called because it will never return true unless x is 0, and thus your x variable is never being incremented. I would suggest looking into the % (modulus) operator for this problem.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have a Java application and want to press a button to generate a 7 digit random number and put it into a text area.
Here is what I have so far:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextArea1.setText();
}
How do I do this?
i don't know what to write inside the brackets to get this random number of seven digits on the text area.
You can use a StringBuilder and append 7 random numbers between 0 and 9 using the nextInt(int n) method :
Random r = new Random();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < 7; i++)
sb.append(r.nextInt(10));
jTextArea1.setText(sb.toString());
first you'll need to inport the java random number library at the top of your code, like this:
import java.util.Random;
this code will get you a random number from 1000000 to 9999999, it is a little weird, but take some time trying to figure it out
1000000 + (int)(Math.random() * ((8999999) + 1))
Try putting that between the parenthasis after setText, like this:
jTextArea1.setText(1000000 + (int)(Math.random() * ((8999999) + 1)));
For more information about the random function and how it works, looks here