I have a method that returns a random value.
public int newRandom() {
Random random = new Random();
int o = random.nextInt(9 - 0 + 1) + 0;
return o;
}
After I generate that value I'm currently setting a variable inside another method to the result of this function, what I want to do is have another class know the same result that variable has, what I mean is both having the same random number, I for some reason can't figure this out on my own. What would be the best way of achieving this?
Do you mean something like that?
import java.util.Random;
public class A
{
public static Random random = new Random();
}
public class B
{
public int getRandomInt()
{
return A.random.nextInt();
}
}
Create a Base class with a public static variable and when you inherit these new classes from the Base class and create new instances they share this same variable:
import java.util.Random;
class Base_class {
public static int o;
public Base_class() {
}
public int newRandom() {
Random random = new Random();
o = random.nextInt(9 - 0 + 1) + 0;
return o;
}
public int get_randn() {
return o;
}
}
class Derived_class1 extends Base_class {
public Derived_class1() {
}
}
class Derived_class2 extends Base_class {
public Derived_class2() {
}
}
class Main{
public static void main(String [] args){
Derived_class1 obj1 = new Derived_class1();
Derived_class2 obj2 = new Derived_class2();
obj1.newRandom();
System.out.println(obj1.get_randn());
System.out.println(obj2.get_randn());
}
}
Consider using composition where multiple objects (could be different classes) share the same instance of a class which provides the random values. For example, given this class to keep track of random values:
private class RandomProvider {
private final Random random = new Random();
private int currentValue;
private int newRandom() {
currentValue = random.nextInt(10);
return currentValue;
}
private int getCurrentValue() {
return currentValue;
}
}
and another class (or classes) which use a RandomProvider:
private class A {
private final RandomProvider randomProvider;
private A(RandomProvider randomProvider) {
this.randomProvider = randomProvider;
}
private int getCurrentRandomValue() {
return randomProvider.getCurrentValue();
}
}
So then a couple instances of A (or some other class) can use the same instance of RandomProvider:
RandomProvider randomProvider = new RandomProvider();
System.out.println("new random value is " + randomProvider.newRandom());
A a1 = new A(randomProvider);
System.out.println("A1 sees current random value as " + a1.getCurrentRandomValue());
A a2 = new A(randomProvider);
System.out.println("A2 sees current random value as " + a2.getCurrentRandomValue());
randomProvider.newRandom();
System.out.println("A1 sees current random value as " + a1.getCurrentRandomValue());
System.out.println("A2 sees current random value as " + a2.getCurrentRandomValue());
Sample output:
new random value is 9
A1 sees current random value as 9
A2 sees current random value as 9
A1 sees current random value as 3
A2 sees current random value as 3
Related
I have two classes
Class 1
public class Random {
public static int random() {
Random random = new Random();
return random.nextInt(10);
}
public static int number = random();
}
And Class 2
public class SecondClass {
static int generatedNumber = Random.number;
public static void main(String[] args) {
System.out.println(generatedNumber);
}
}
Every time I try to access the generatedNumber variable of Class 2 from a third Class, the number I get is different and not the one received in Class 2.
My question is how I can make the number generated in Class 2 persist to be able to call it from other Classes and that it is always the same number generated in Class 2.
You asked me to show you:
public class FixRandom {
// Holds the fixed random value.
private final int fixedValue;
// Upper bound for the RNG.
private static final int BOUND = 10;
// Constructor.
public FixRandom() {
// Set the fixed random value.
Random rand = new Random();
fixedValue = rand.nextInt(BOUND);
}
// Method to access the fixed random value.
public int getFixRandom() {
return fixedValue;
}
}
When you need to retrieve the number, use the getFixRandom() method.
Final(?) edit:
Leonardo Pina's solution looks like what I needed. Thank you all for your input! My code is now:
public final class Roll {
private static final Random r1 = new Random();
private final int r = level();
private static final int level() {
int s = 1, e = 100;
int r = r1.nextInt((e - s) + 1) + s;
return r;
}
public int itemType() {
boolean b = r1.nextBoolean();
int a = ((b) ? 1 : 2);
return a;
}
public int getR() {
return r;
}
}
And the implementation in the other class:
public class Damage {
Roll r;
Damage(Roll r) {
this.r = r;
}
public int damageOut() {
int a = r.getR(); //roll value
return a * 2; //test math on r
}
}
Edit:
Thank you for the responses. However, it seems my use of this method was not clear. Apologies! This is what I need:
Call Roll class, get e.g. "12"
OtherClass1 receives "12" from Roll via getter
OtherClass2 also receives "12" from Roll via getter
Call Roll class again, get a new random number, e.g. "48"
OtherClass1 receives "48" from Roll via getter
OtherClass2 also receives "48" from Roll via getter
Using the solutions provided, Roll creates a single random number and never creates a new one again. I need Roll to create random numbers on demand, and then share that random number with other classes. I do not want it to only generate one number and then stop. I hope this makes sense. Thank you for the responses so far!
I have searched for and read the other threads of a similar topic (including this one, which is how I tried to solve my problem), but the methods I have tried have failed. I need to create a single random value and then use that same value across multiple classes.
My random class:
public final class Roll {
private static final Random r1 = new Random();
private final int r = level();
private static final int level() {
int s = 1, e = 100;
int r = r1.nextInt((e - s) + 1) + s;
return r;
}
public int itemType() {
boolean b = r1.nextBoolean();
int a = ((b) ? 1 : 2);
return a;
}
public int getR() {
return r;
}
}
And a class where I call for the static value from the random class:
public class OtherClass{
Roll roll = new Roll();
int r = roll.getR();
public int getR() {
return r;
}
}
When I call the getter from OtherClass, the value is different than the getter from Roll. I would expect them to be the same value.
I call the values for testing like so:
Roll roll = new Roll();
int r = roll.getR();
OtherClass other = new OtherClass();
int o = other.getR();
Any guidance would be greatly appreciated. Have a good day.
When you create a new instance of OtherClass you also create a new instance of Roll, therefore, the rolls are different.
You need to make sure you are getting the value R from the same object Roll.
This could be achieved by using a singleton pattern for the Roll class, or you could specify the Roll object you want to use to get values, this way you could have several rolls for different purposes. i.e.
Edit:
Answering your edit: to get a new number, you should update the value of r in the Roll class whenever you generate a new value, for example, instead of returning a value, the level() method could update the r variable:
public final class Roll {
private static final Random r1 = new Random();
// We now attribute a value to r uppon construction
private final int r;
public Roll() {
level();
}
// Whenever level() is called the value of r is updated
private static final int level() {
int s = 1, e = 100;
int r = r1.nextInt((e - s) + 1) + s;
this.r = r;
}
public int itemType() {
boolean b = r1.nextBoolean();
int a = ((b) ? 1 : 2);
return a;
}
public int getR() {
return r;
}
}
class Game {
public static void main(String[] args) {
// Create the Roll obj
Roll myRoll = new Roll();
// Initialize the other objs with myRoll
Board board = new Board(myRoll);
Player player = new Player(myRoll);
// Do your comparison
int b = board.getRoll();
int p = player.getRoll();
// EDIT: get a new value
myRoll.level();
// Do your comparison once more
b = board.getRoll();
p = player.getRoll();
}
class Board {
Roll r;
Board(Roll roll) {
this.r = roll;
}
public int getRoll() {
return r.getR();
}
}
class Player {
Roll r;
Player(Roll roll) {
this.r = roll;
}
public int getRoll() {
return r.getR();
}
}
}
Probably the simplest way to make it work would be to field r in class Roll as static, so that the Roll class looks like this:
ublic final class Roll {
private static final Random r1 = new Random();
private static final int r = level();
private static final int level() {
int s = 1, e = 100;
int r = r1.nextInt((e - s) + 1) + s;
return r;
}
public int itemType() {
boolean b = r1.nextBoolean();
int a = ((b) ? 1 : 2);
return a;
}
public int getR() {
return r;
}
}
Or second approach would be to make Roll class a singleton.
Edit:
Since you have changed the intent of the question, and from what I understand you should look into Observer design pattern. It may be helpful for your case.
As someone said in the comments, you should follow the singleton design pattern, meaning that your variable r should be unique across all Roll class instances. To do this, your code will have to look something like this:
public class RandomTest {
public static void main(String[] args) {
Roll roll = new Roll();
int r = roll.getR();
OtherClass other = new OtherClass();
int o = other.getR();
}
}
class Roll {
private static Random r1 = new Random();
private static int r = level();
private static final int level() {
int s = 1, e = 100;
int r = r1.nextInt((e - s) + 1) + s;
return r;
}
public int itemType() {
boolean b = r1.nextBoolean();
int a = ((b) ? 1 : 2);
return a;
}
public int getR() {
return r;
}
}
class OtherClass{
Roll roll = new Roll();
int r = roll.getR();
public int getR() {
return r;
}
}
How about sharing the Roll instance?
Roll roll = new Roll();
// roll.roll(); // Unclear how you "refresh" the data
int r = roll.getR();
OtherClass other = new OtherClass(roll);
int o = other.getR();
assert(o == r);
class OtherClass {
private final Roll roll;
public OtherClass(Roll roll) {
this.roll = roll;
}
public int getR() {
return roll.getR();
}
}
Tip: I think a Dice class with a roll() method makes more sense.
Im a newcomer :)
However, my program has a table and a RandomGen should get the highest random int by getRowCount -> checkvar1.
Now, the main class gets checkvar1 and sends it to setVariable(), then I want to exchange this checkvar1 with randomGen to limit the maximum generated integer.
So this of course doesn't work because the parameters in randomGen() aren't set and I cannot set them, because then the exchange to the onActionPerformed() method in my main class doesn't work anymore.
public final class RandomGen
{
// EXCHANGE OF CHECKVAR1 FOR RANDOM GEN
public static void setVariable(int checkvar1)
{
System.out.print(checkvar1);
}
// RANDOM GENERATOR
public static int randomGen()
{
Random rand = new Random();
int var1 = rand.nextInt(checkvar1) + 1;
return var1;
}
}
Here my main class:
public void onActionPerformed(java.awt.event.ActionEvent evt) {
//NUMBER OF LAST ROW
int checkvar1 = (Integer)jTable1.getRowCount();
//->EXCHANGE WITH setVariable()
RandomGen.setVariable(checkvar1);
if (checkvar1 >= 3) {
int recogvar1 = checkvar1 - 1;
Object checkobj1 = jTable1.getModel().getValueAt(recogvar1, 0);
if (checkobj1 == null){
//...
}
else {
int var1 = RandomGen.variable();
String result = var1 + "";
jTextField1.setText(result);
//System.out.print(result);
}
}
else {
String rule2 = "At least " + 3 + " rows should be filled";
jTextField1.setText(rule2);
}
You are doing nothing with your setVariable in your class RandomGen. So You only need to change this.
// RANDOM GENERATOR
public static int randomGen(int checkvar1)
{
Random rand = new Random();
int var1 = rand.nextInt(checkvar1) + 1;
return var1;
}
And in your main Method try this.
//NUMBER OF LAST ROW
int checkvar1 = (Integer)jTable1.getRowCount();
//->EXCHANGE WITH randomGenerator
checkvar1 = RandomGen.randomGen(checkvar1);
So I am relatively new to the programming scene and I am confused as to why my code doesn't work. I am trying to make an arraylist of flowers and then use a random number generator to create a random number of certain flowers, and store them in the array. In my logic, I thought that I created a variable to store the numbers (ex randomRoses) and stored the number in the array so I could easily print out how many of each flower there is by just calling the arraylist and the position. (ex flowerArray[0] would print out 8 Roses) but sadly it does not.
public class Flower
{
private int randomRoses;
private int randomTulips;
private int randomOrchids;
public ArrayList <Integer> flowerArray;
public Flower()
{
r = new Random();
t = new Random();
o = new Random();
int randomRoses = (r.nextInt(10) + 0);
int randomTulips = (t.nextInt(10) + 0);
int randomOrchids = (o.nextInt(10) + 0);
flowerArray = new ArrayList<Integer>
}
public void add2Array ()
{
flowerArray.add(randomRoses); //flowerArray[0] is the # of roses
flowerArray.add(randomTulips); //flowerArray[1] is the # of tulips
flowerArray.add(randomOrchids); //flowerArray[2] is the # of orchids
}
public void printArray()
{
System.out.println(flowerArray[0]);
}
You can use the same random object, no need to create 3 instances of it for the random integer generation,
Random r = new Random();
for (int i = 0; i < 3; i++) {
flowerArray.add(r.nextInt(10));
}
System.out.println(flowerArray);
you can not do flowerArray[0] because you have an arrayList and not an array.
you can instead do: flowerArray.get(0) for getting the integer at pos zero
Here your array list is associated with a class object. When you initialize your array list you need to add your entries to the array list in the constructor itself. So when you say object.printArray() its actually returning you the empty array list, that's why you are getting 0 every time. Try This.
class Flower
{
private int randomRoses;
private int randomTulips;
private int randomOrchids;
public ArrayList<Integer> flowerArray;
public Flower()
{
Random r = new Random();
Random t = new Random();
Random o = new Random();
int randomRoses = (r.nextInt(10));
int randomTulips = (t.nextInt(10));
int randomOrchids = (o.nextInt(10));
System.out.println(randomRoses);
System.out.println(randomTulips);
System.out.println(randomOrchids);
flowerArray = new ArrayList<Integer>();
flowerArray.add(randomRoses); //flowerArray[0] is the # of roses
flowerArray.add(randomTulips); //flowerArray[1] is the # of tulips
flowerArray.add(randomOrchids); //flowerArray[2] is the # of orchids
}
public void printArray()
{
System.out.println(flowerArray.get(0));
}
}
public class Test {
public static void main(String[] args) {
Flower f = new Flower();
f.printArray();
}
}
And in array list you can get elements by using get(index) method.
This will give the output you expect.
public void printArray
{
System.out.println(flowerArray.get(0)+" Roses");
System.out.println(flowerArray.get(1)+" Tulips");
System.out.println(flowerArray.get(2)+" Orchids");
}
Also you missed a semi-colon after the statement defining the arraylist.
Make the correction:
flowerArray=new ArrayList<Integer>;
How did it compile without that semi-colon?
It is not working because your syntax for getting the ith flower is wrong.
You're using a java.util.ArrayList so the correct way to get an object from that ArrayList is by calling the get() method.
System.out.println(flowerArray.get(0));
Hope that helps.
I am trying to randomly grab integers from another class and cannot figure out how to get those values. The first class is my initial random number generator. The second class is the class I am trying to retrieve these numbers to. I have created a grab method but cannot figure out how to retrieve these random integers from class ArrayBag. Any help would be appreciated!
import java.util.Random;
public final class ArrayBag<T> implements BagInterface<T>
{
private final T[] bag;
private int numberOfEntries;
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 6;
private static final int MAX_CAPACITY = 10000;
/** Creates an empty bag whose initial capacity is 6. */
public ArrayBag()
{
this(DEFAULT_CAPACITY);
System.out.print("Generating 6 random integers 1 - 6 in ArrayBag\n");
//Random loop to generate random numbers 1 to 6
Random rand = new Random();
for(int start=1; start <=6; start++)
{
int randInt = rand.nextInt(6);
System.out.println("Generated : " + randInt);
}
System.out.println("Finished\n");
} // end default constructor
This is my second class and method...
import java.util.Random;
public class PopulationBag
{
public PopulationBag()
{
ArrayBag ab = new ArrayBag();
LinkedBag lb = new LinkedBag();
}
/**
* Grab Method
*/
public int grab()
{
ArrayBag ab = new ArrayBag();
Random grab = new Random();
for(int start = 1; start <= 6; start++)
{
int randGrab = grab.nextInt(ab);
System.out.println("Randomly grabbed values : " + randGrab);
}
}
}
As far as I understant what you are trying to do is to build a class which genereates and holds a user-given number of random ints and second class which can access the values generated by the first class.
I've noticed a few issues with your approach. Firstly, you are generating the random numbers but never store them anyway. If the number of random ints is given by a user, you can try ArrayList approach, or use a new Java 8 approach with the method ints() of Random class (which I used in the code below). You would also need a getter method to make the access to your private variable possible.
Consider the code:
public class ArrayBag {
private int[] randomBag;
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 6;
private static final int MAX_CAPACITY = 10000;
public ArrayBag() {
Random random = new Random();
randomBag = new int[DEFAULT_CAPACITY];
// The method ints introduced in Java 8 accepts three params:
// number of ints generated, upper and lower bound between which the ints will be generated.
// toArray method passes the generated nums as an dynamically created array,
// which you can assign to a variable.
randomBag = random.ints(DEFAULT_CAPACITY, 1, DEFAULT_CAPACITY + 1).toArray();
}
// the 'getter' method
public int getRandomInt(int i) {
return randomBag[i];
}
}
/* Second class */
public class PopulationBag {
private ArrayBag ab = new ArrayBag();
private Random grab = new Random();
// Are the numbers form the ArrayBag going to be grabbed at random,
//or simply one after another?
public int[] grabInOrder(int numberOfGrabbedInts) {
// Create an array to hold ints.
int[] intBag = new int[numberOfGrabbedInts];
// Fill in data to the intBag
for (int i = 0; i < numberOfGrabbedInts; i++) {
// Call getRandomInt() method form ArrayBag class
intBag[i] = ab.getRandomInt(i);
System.out.println("Randomly grabbed values : " + intBag[i]);
}
return intBag;
}
private int[] grabAtRandom(int numberOfGrabbedInts) {
int[] intBag = new int[numberOfGrabbedInts];
for (int i = 0; i < numberOfGrabbedInts; i++) {
// This is kind of funky, basically it returns at random the ints saved in ArrayBag.
intBag[i] = ab.getRandomInt(grab.ints(1, 1, numberOfGrabbedInts).findFirst().getAsInt());
System.out.println("Randomly-randomly grabbed values : " + intBag[i]);
}
return intBag;
}