Advice with for loop programs - java

I get the general gist of for loops. I want to know how I could add two variables to the initializer. I also want to count counter and random at the same time. I want it to prints random but not to print 30 of the same number
public class forLoop {
public static void main(String[] args) {
int random = (int) (Math.random() *50) +25;
for(int counter = 0; counter < 30; counter++){
System.out.println(random);
}
}
}

You're generating the random number outside of your loop. Therefore it will exist as the same number every time. The solution is to move the definition inside of the loop.
public static void main(String[] args) {
for(int counter = 0; counter < 30; counter++){
int random = (int) (Math.random() *50) +25;
System.out.println(random);
}
}
In this way, every time through the loop (30 iterations), your code will (1) generate some random number and (2) print that number.

random is getting set to a particular random integer before the loop starts. You are not defining random to be (int) (Math.random() *50) +25 but rather you are executing that and setting random to the result.
The loop then prints out the same thing each time. If you want a new random each time, then you will need to move that statement inside the loop.

Related

Java Random setSeed() not deterministic

I have a class called 'Face' that creates a static instance of java.util.Random:
public static Random random = new Random();
Then, in Main, I set the seed and get a random value:
Face.random.setSeed(1);
int rand = Face.random.nextInt(5);
The value of 'rand' is different every time I run the program, though. I need it to be the same every time. I thought setting a seed did this, but I must not understand correctly. What am I missing?
If you are always setting the seed for every call, then it appears that the sequence of random numbers will be reset.
Try
random.setSeed(1);
for (int i = 0; i < 5; i++) {
int rand = random.nextInt(5);
System.out.println(rand);
}

How to initialize an Integer Array with multiple values while using "for"

While I was trying to create a small GUI in Java, I've stumbled onto this small issue with arrays.
I've tried inserting Random Integers into an one dimensional array, only to find out that the Random Integers won't get assigned.
//Declaring an Integer Array
int[] wuerfel = new int[2];
//It will loop once while assigning a random number to the array
for(int i = 0; i <= 1; i++) {
Random rand = new Random(6);
int zahlen = rand.nextInt(6) + 1;
wuerfel[i] = zahlen;
}
System.out.println(Arrays.toString(wuerfel));
I expect the output from the array to be a number between 1 - 6.
However, I keep receiving [2,2] as a result every time I try to rerun.
The constructor call new Random(6) doesn't do what you think it does: 6 is the seed, rather than the range of possible outputs. Therefore it will produce the same output every time.
Possible solutions:
Use the no-argument constructor for Random() instead, which will give it a different seed each time.
Declare and initialise rand outside the loop, with or without an explicit seed.
Use Math.random().
So in your code you set up a seed for your Random and you create new Random object every loop iteration so it just returns same number every time. If you use seed the documentation of Random class says :
If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.
In your case you can get rid of seed value from your constructor or move Random class object creation outside of the loop :
public static void main(String[] args) {
int[] arr = new int[2];
Random rand = new Random();
for(int i = 0; i <= 1; i++) {
int zahlen = rand.nextInt(6) + 1;
arr[i] = zahlen;
}
System.out.println(Arrays.toString(arr));
}
Here I moved creation of Random instance outside of the loop so only one object is created and I am not passing seed to the constructor. I could pass the seed but in this case it is not needed as I don't need to create more instances of Random and I dont need them to generate same results.
*
int[] wuerfel = new int[2];
//It will loop once while assigning a random number to the array
Random rand = new Random();
for(int i = 0; i <= 1; i++) {
int zahlen = rand.nextInt(6) + 1;
wuerfel[i] = zahlen;
}
System.out.println(Arrays.toString(wuerfel));
* try this one create Random object with passing parameter

Randomly generated number of X's

I need a program to randomly generate a number, and then out put that number of x's, on there own line, until it outputs a line of 16 x's, and then it will stop. So far my program generates a number but never stops outputting. I'm sure this is my error but not sure what needs to change. Here is my code at this moment.
import java.util.Random;
public static void main(String[] args)
{
toBinary();
randomX();
}
public static void randomX()
{
Random num = new Random();
int ran = num.nextInt(16+1);
int xs = ran;
while(xs <= 16)
{
System.out.print("x");
}
}
Your version has a number of small issues. Here's a suggested set of revisions.
// create your random object outside the method, otherwise
// you're instantiating a new one each time. In the long run
// this can cause awkward behaviors due to initialization.
public static Random num = new Random();
public static void randomX(){
int ran;
do {
ran = 1 + num.nextInt(16); // move the +1 outside unless you actually want 0's
int counter = 0;
while(counter++ < ran) {
System.out.print("x");
}
System.out.println(); // add a newline after printing the x's in a row
} while(ran < 16);
}
The biggest issue is that you need two loops, an outer one for generating new numbers and an inner one for printing the current number of x's.
A secondary problem was that your loop was checking for numbers <= 16. All of your values are <= 16, so it was an infinite loop.
Additional suggestions found in the comments.
To approach this, think of the loops you might need.
You need to print x a certain number of times, that's a loop. I also introduce a variable to keep track of this printing.
You need to keep printing until you hit 16. That's another loop.
public static void randomX(){
Random num = new Random();
int xs = 0;
//This loop keeps going until you reach 16
while(xs <= 16){
xs = num.nextInt(16+1);
int x = 0;
//This loop keeps going until you've printed enough x's
while (x < xs)
{
System.out.print("x");
x++;
}
System.out.println("")
}
}
You can use a auxiliary counter to manage the loop and increase it to exit the loop.
int i = 0;
while (i<xs){
System.out.print("x");
i++;
}
You can check more about java loops here:
Tutorial about java while

Java Dice Simulation

I am writing a dice roll program. The code works fine in working out the face and number of frequencies. How I can calculate the percentage for the frequency of each face?
import java.util.Random;
public class Dice{
public static void main (String[] args){
Random random = new Random(); // Generates random numbers
int[] array = new int[ 7 ]; // Declares the array
//Roll the die 10000 times
for ( int roll = 1; roll <=10000; roll++ ) {
/*++array[1 + random.nextInt(6)];*/
int dice = 1 + random.nextInt(6);
++array[dice];
}
System.out.printf("%s%10s\n", "Face", "Frequency");
// outputs array values
for (int face = 1; face < array.length; face++) {
System.out.printf("%4d%10d\n", face, array[face]);
}
}
}
The frequency is just the count of each face divided by the total count.
for (int face = 1; face < array.length; face++) {
System.out.printf("%4d%10f\n", face, array[face] / 10000.0);
}
The division must be performed with a double value (otherwise, an integer division would be performed and the result would always be 0), explaining why I divided with 10000.0 and not 10000.
I also changed the String format from %10d to %10f because you want to print a decimal number, not an integer. See the Formatter Javadoc for the list of all token.
Also, I suggest you make a local variable holding the total count so as not to repeat it twice.

Attempting to create chance calculator

I am relatively new to Java and wanted to try and make a code that would randomly generate 2 numbers a set amount of times, and it would track how many times the 2 numbers are the same. Then after X amount of attempts it would calculate the chance of it happening.
# of randoms divided by times they were the same
import java.util.Random;
public class RandomTest {
public static void main(String[] args) {
int[] anArray;
anArray = new int[100000];
Random randomGenerator = new Random();
for (int loop = 1; loop < 1000; loop++) {
int random1 = randomGenerator.nextInt(100);
int random2 = randomGenerator.nextInt(100);
if (random1 == random2) {
int number = number + 1;
countArray[number] = loop;
}
if (loop == 1000) {
System.out.println("Took " + loop + " randoms.");
break;
}
else {}
}
}
}
Main issue seems to be getting array to fill and to get ints in/out of the loop.
Here is my version of your code:
import java.util.Random;
import java.util.ArrayList;
public class RandomTest {
public static void main(String[] args) {
ArrayList<Integer> duplicates = new ArrayList<Integer>();
int random1 = 0, random2 = 0;
Random randomGenerator = new Random();
for (int loop = 1; loop <= 1000; loop++) {
random1 = randomGenerator.nextInt(100);
random2 = randomGenerator.nextInt(100);
if (random1 == random2) {
duplicates.add(new Integer(random1));
}
}
for (Integer i : duplicates) {
System.out.println("Duplicate: "+i.toString());
}
}
}
There are a number of problems that your solution contains:
int number = number + 1;
The above will create a new int called number and give it the value null + 1, this is because the above can be split into 2 lines:
int num;
num = num + 1;
The first line will reserve memory space for a variable called num. The second line will try and put the value of (num + 1) into num. As we are calling num and it has not been initialised - this will give us a java.lang.Error (at least that is what I got).
So as you can see, putting number outside the for loop and initialising it like this:
int number = 0;
for (int loop = 1; loop <= 1000; loop++) {
number = number + 1;
}
Will increment the value of number by 1, 999 times.
Which brings me to the next point. The for loop will never make loop = 1000 because the condition will stop the loop before the condition is true, so when the for loop finishes, loop will equal 999. If you wanted the loop to finish on loop = 1000 you should use loop <= 1000. Also, the if condition is not necessary as when the loop finishes it will just carry on with the rest of the code beneath it.
I haven't used number at all in my solution, this is because I used an ArrayList, which is essentially a much more advanced version of an array that can grow dynamically and do loads of other cool stuff. Unfortunately ArrayLists need to contain objects, so I wrap each int inside an Integer object and this is fine. At the end I use a for loop to iterate through the duplicates list, for each result I print it out.
Hope this helps and if you have any questions feel free to comment beneath.
You probably want to do something about this line:
int number = number + 1;
To step through the array, set number to zero
int number = 0;
before entering the loop then increment number with
number = number + 1;

Categories