I'm trying to create a Java program that generates an amount of seats taken in an airplane. So far, I have been able to do this, but my problem is every time I run the client the numbers generated are different. I need them to be the same every time...
I'm not sure what I'm doing wrong, can anybody help me?
import java.util.Random;
import java.util.Arrays;
public class Airplane {
public static Random randomNumbers = new Random();
public static int[] oSeatLeft = new int[10];
public static int[] mSeatLeft = new int[10];
public static int[] wSeatLeft = new int[10];
public static int oSeat = 0;
public static int mSeat = 0;
public static int wSeat = 0;
public static final int sCheck = 0;
public void genWSeats() {
int randSeatFill = 0;
if (wSeat == 0) {
for (int counter = 0; counter < wSeatLeft.length; counter++) {
randSeatFill = randomNumbers.nextInt(2);
if (randSeatFill == 1) {
wSeatLeft[counter] = 1;
}
}
if (wSeat == 0) {
wSeat++;
}
}
}
public int[] getWSeats() {
System.out.println(java.util.Arrays.toString(wSeatLeft));
return wSeatLeft;
}
}
The purpose of static int wSeat is supposed to be a checker. If wSeat is greater than zero, then it should not randomly generate numbers for the array. Not sure exactly what is going wrong here....
Use the Random constructor with seed
public static Random randomNumbers = new Random(42);
This way always the same sequence of random numbers is generated.
42 is only an example, you can use any value you want.
Pass a seed on initialization with Random(long seed). This will guarantee that the sequence of numbers generated is always the same (since it's a pseudo-random number generator).
Pass Seed in constructor of Random it will generate the same number every time
Related
here's the array I want to rerun:
public static int[] rollDice(int dice[]) {
// generate 5 random numbers / update dice array
for (int i = 0; i < dice.length; i++) {
dice[i] = (int)(Math.random() * 6 + 1);
}
return dice;
}
If I want to reset this array and find new random numbers how would I do that? I tried rollDice() only to get an error.
There is no point in returning the array, since you already have a reference to the array when you call the method rollDice().
Arrays are sent by reference and not by value, which means you are not working with a copy like you do with ints, instead you are modifing the original array.
Change the return type to void and remove the return and your code should work as intended.
You can get every time a new dynamic length array with random numbers, and you can access by call rollDice(integer value).
public static int[] rollDice(int length) {
final int dice[] = new int [length];
// generate array with random values
for (int i = 0; i < length; i++) {
dice[i] = (int)(Math.random() * length + 1);
}
return dice;
}
You would have to have a class member like this:
public static final int[] dice = new int[5];
Then to roll/reroll the dice use your method, else just access dice.
public static void rollDice() {
// generate 5 random numbers / update dice array
for (int i = 0; i < dice.length; i++) {
dice[i] = (int)(Math.random() * 6 + 1);
}
}
Interesting fact: Java has no static function variables as C and C++ does. In those languages it could look like this:
(I wrote it like a java Function for you Java guys)
public static int[5] rollDice(boolean reroll) {
static final int[] dice = new int[5];
if (reroll) for (int i = 0; i < dice.length; i++) {
dice[i] = (int)(Math.random() * 6 + 1);
}
return dice;
}
As you can see, static variables can be embedded into those functions. If you ask me, it's a huge minus, Java doesn't support this as I use it all the time to hide those from the class namespace.
I tried attempting this but I think I'm doing something wrong. I am a beginner level programmer and I really need help on this. I feel like I'm close to the answer but I'm not sure what's wrong with my program. I try checking my answer by square rooting the Variance result to get Standard Deviation but they don't match.
import java.util.Random;
public class Lab6 {
public static void main(String[] args) {
System.out.println("The Average Value is:"+avgValue());
System.out.println("The Standard Deviation is:"+stdDev());
System.out.println("The Variance is:"+Var());
}
public static int randomFill(){
Random rand = new Random();
int randomNum = rand.nextInt();
return randomNum;
}
private static int[] anArray;
public static int[] list() {
anArray = new int[100];
for(int i=0;i<anArray.length;i++)
{
anArray[i] = randomFill();
}
return anArray;
}
private static int sum;
public static int avgValue() {
int []a = list();
for (int e:a)
{
sum +=e;
}
int n=100;
sum=sum/n;
return sum;
}
private static int pwr;
public static int stdDev() {
int []b = list();
int dev=0;
for (int e:b)
{
dev=(e-sum)+dev;
}
pwr=(dev*dev)/99;
double root=Math.sqrt(pwr);
return pwr;
}
public static int Var() {
int c= pwr;
int opp=c*c;
return opp;
}
}
Its been a while since I did statistics but I can point out that your avgValue() method and your stdDev() are computing against two different int arrays. When you call list() you get a different array of integers each time and overwrite anArray.
I'd recommend creating the array inside your main method and then passing it as a parameter to the other methods. If you want to go the route you're on, change "int []b = list();" to "int []b = anArray;" and you should be fine.
Overall I think you might want to try looking into method parameters and variable scope next to improve your Java. Keep on truckin'; it gets easier.
I don't recall the variance and standard deviation formulas correctly, but one mistake related to programming logic in your code is that you have called list() once while calculating the average and once while calculating the standard deviation.
Every call to your list() method returns a new array with new random values. So, essentially, even if you calculate standard deviation correctly from the code, the average you consider (i.e the sum variable) corresponds to the average of some other array.
public static void main(String... args) {
int[] arr = createRandomArray(100);
System.out.printf(Locale.US, "The Average Value is: %.2f\n", mean(arr));
System.out.printf(Locale.US, "The Standard Deviation is: %.2f\n", standardDeviation(arr));
System.out.printf(Locale.US, "The Variance is: %.2f\n", variance(arr));
}
public static int[] createRandomArray(int total) {
int[] arr = new int[total];
Random random = new Random();
for (int i = 0; i < arr.length; i++)
arr[i] = random.nextInt(100);
return arr;
}
public static double mean(int[] arr) {
return (double)Arrays.stream(arr).sum() / arr.length;
}
public static double standardDeviation(int[] arr) {
double mean = mean(arr);
double sum = IntStream.range(0, arr.length)
.boxed()
.map(i -> Math.pow(arr[i] - mean, 2))
.mapToDouble(d -> d)
.sum();
return Math.sqrt(sum / arr.length);
}
public static double variance(int[] arr) {
return Math.pow(standardDeviation(arr), 2);
}
While trying to create a Coin object class using two specific seeds passed into the object upon creation, I have noticed that when passing in the seed to an int "seed", the seed variable produces a different variable than just inputting the specific number into the random number generator. Here's some code from the Coin class:
public int headCount;
public int tailCount;
public int seed;
public Coin( int n ){
seed = n;
headCount = 0;
tailCount = 0;
}
public Random flipGenerator = new Random(seed);
public String flip(){
String heads = "H";
String tails = "T";
boolean nextFlip = flipGenerator.nextBoolean();
if (nextFlip == true)
{
headCount++;
return heads;
}
if (nextFlip == false)
{
tailCount++;
return tails;
}
return null;
}
Here's from the file that creates and prints the Coin objects:
Coin coin1 = new Coin( 17 );
Coin coin2 = new Coin( 13 );
The code in that file prints out the outcome of the random flips 20 times using the 17 seed, 10 times with the 13 seed and finally 35 times with the 17 seed again. However the output is incorrect when using
public Random flipGenerator = new Random(seed);
as opposed to
public Random flipGenerator = new Random(17);
or
public Random flipGenerator = new Random(13);
Why is this happening?
Instance fields are initialized before the constructor is called.
In terms of execution order, this code:
public int headCount;
public int tailCount;
public int seed;
public Coin( int n ){
seed = n;
headCount = 0;
tailCount = 0;
}
public Random flipGenerator = new Random(seed);
is functionally equivalent to this:
public int headCount;
public int tailCount;
public int seed;
public Random flipGenerator = new Random(seed);
public Coin( int n ){
seed = n;
headCount = 0;
tailCount = 0;
}
In Java, any fields which were not explicitly initialized are given a value of zero/null/false, so you are always doing flipGenerator = new Random(0). By the time you initialize seed in your constructor, the Random object has already been created. The fact that the instance field was declared after the constructor is irrelevant, because all instance fields and their initialization expressions are executed before a constructor is invoked.
Whenever you initialize the Coin class it will use 0 as the seed. Regardless if you put the flipGenerator initialization below the constructor, it will still get called in the constructor since it is an instance variable.
Coin coin1 = new Coin( 17 );
Coin coin2 = new Coin( 13 );
This code is using 0 because, by the time you pass the seed, the flipGenerator was initialized with the default seed of 0.
You need to do this
public int headCount;
public int tailCount;
public int seed;
public Random flipGenerator;
public Coin( int n ){
seed = n;
headCount = 0;
tailCount = 0;
flipGenerator = new Random(seed);
}
...
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Issue: I've completed steps 1-4 of this assignment. However, I'm currently stuck on steps 5 and 6 of this assignment, so I'm at a loss on how to combine my fizz and buzz String arrays into a separate fizzbuzz String array.
TL;DR I don't know how to do steps five and six.
Assignment:
You can do this all in the main method. This is using a game called
Fizz-Buzz, an ancient programmer’s game.
Start by initializing some variables to set the maximum and minimum value of a random number and for the capacity of an array.
(20/100)
Initialize three new arrays, one for a list of random numbers (as integers) and two for String arrays called ‘fizz’ and
‘buzz’.(20/100)
You’ll also need an integer for counting.
Write a for loop that generates a random number for each position in the array. Remember that the range for this will be set by
the two variables initialized at the beginning of the file. There are
multiple ways to create a random number, just find one that works for
you. (20/100)
Using the count of the arrays, create another array that will store all of the fizzes and buzzes without any extra space leftover in
the array. (20/100)
Use a for each loop to iterate the array and print all of the fizzes and buzzes, with no other output. (20/100)
What I've accomplished thus far:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.Random;
/**
*
* #author
*/
public class FizzBuzz {
//2a. Initialize one int array for a list of random numbers.
private static int[] anArray;
private static final int size = 10;
//2b. Initialize two String arrays called 'fizz' and 'buzz.'
public static String[] fizz;
public static String[] buzz;
public static String[] fizzbuzz;
public static Random rand = new Random();
//1. Set the maximum and minimum value of a random number.
private static final int min = 0;
private static final int max = 5;
private static int count = 0;
public static int[] list() {
anArray = new int[size];
//3. Make an integer for counting("counter" in the for loop)
//4. Write a for loop that generates a random number for
// each position in the array.
for(count = 0; count < anArray.length; count++) {
anArray[count] = randomFill();
}
return anArray;
}
public static void print() {
for (int i = 0; i < anArray.length; i++) {
System.out.println(anArray[i] + ": " + fizz[i] + buzz[i]);
}
}
public static int randomFill() {
return rand.nextInt((max - min) + 1) + min;
}
public static String[] getF() {
fizz = new String[size];
int x = 0;
int counter;
for(counter = 0; counter < fizz.length; counter++) {
if(anArray[counter] % 3 == 0) {
fizz[counter] = "fizz";
} else {
fizz[counter] = "";
}
}
return fizz;
}
public static String[] getB() {
buzz = new String[size];
int x = 0;
int counter;
for(counter = 0; counter < buzz.length; counter++) {
if(anArray[counter] % 5 == 0) {
buzz[counter] = "buzz";
} else {
buzz[counter] = "";
}
}
return buzz;
}
public static String[] getFB() {
fizzbuzz = new String[size];
return fizzbuzz;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
list();
getF();
getB();
print();
}
}
First of all:
How Random works
Your implementation of Random won't quite work for simple reason:
If you call the default-constructor, the seed of the PRNG will be the current time, thus you're quite likely starting multiple PRNGs with the same seed and thus receive the same random-value multiple times. Use a single Random-instance instead:
private Random rnd = new Random();
public static int randomFill() {
return rnd.nextInt((max - min) + 1) + min;
}
This should help in understanding the issue better.
General implementation
Try to stick as close to the given task as possible. E.g. the problem explicitly states that you should use a variable to specify the length of the arrays, while you're using a fixed magic-number. The task explicitly states to use two arrays fizz and buzz, you're using one array called fizzbuzz.
Inside GetFizzBuff, you probably meant x = 2; instead of x = x + 2;. Apart from that this part is fine.
Output
As above: try to stick to the given task. It's explicitly stated to only output the fizzes and buzzes, not any integers. Or at least try to print a value and the corresponding fizzes and buzzes in the same line, to produce readable output.
Instead of writing:
Random randomGenerator = new Random();
for (int idx = 5; idx <= 15; ++idx){
int randomInt = randomGenerator.nextInt(1);
each time I need a random number in a function, Is it possible to just pass or call the result from a random number generator class into the function?
For Example, I have one function in particular which is receiving variables from another class
favoriteTracks(String fromExampleClass1, String fromExampleClass1again)
could I do
favoriteTracks(String fromExampleClass1, String fromExampleClass1again, Long fromRNGclass)
for clarification:
My one function "favoriteTracks" requires variables passed from "ExampleClass1".
At the same time, I want it to receive a random number as a variable (or call it, whichever is easiest). generated in another class by
public static long randomNum(){
Random randomGenerator = new Random();
for (int idx = 5; idx <= 15; ++idx){
int randomInt = randomGenerator.nextInt(1);
The simplest approach would be to encapsulate the behaviour you want in a singleton:
public class MyRandom {
public static final MyRandom myRandom = new MyRandom();
private Random randomGenerator = new Random();
public int makeRandom() {
// put your for loop here if you want, but it is not necessary
return 5 + randomGenerator.nextInt(11);
}
}
somewhere else ...
x = MyRandom.myRandom.makeRandom();
That looks like a possible solution for what you are trying to do.