How to create an array with a random amount of values - java

I need to create an array that has a random amount of values from 8 to 12, but it says my variable is incompatible. What do I have to change? Should x not be an int?
Here is the first part of the code that includes the problem:
public class Fish {
int min = 8;
int max = 12;
int x = min + (int)(Math.random() * ((max-min) + 1));
static Fish[] myFish = new Fish[x];
static int Fcount=0;
private float weight;
public Fish(float w) { weight = w;
myFish[Fcount] = this;
Fcount++;
}
public float getWeight( ) { return weight; } }
The second part of my code is:
public class GoFish {
public static void main(String[] args) {
float[] myWeights;
for (int i = 0 ; i < x ; i++){
int min = 1;
int max = 20;
myWeights[i] = min + (int)(Math.random() * ((max-min) + 1));
}
for ( float w : myWeights ) { new Fish(w); }
for ( Fish f : Fish.myFish ) {
System.out.println( f.getWeight() );
} } }
Could you also explain the problem, because I would like to understand what I'm doing wrong. I also have to make the weight a random number between 1 and 20, but I can't get this type of random numbers to work.
Edit: Since we are making the x variable static, how do I use it in the other file? because I need the array values to be random.

x is an instance variable. You're trying to access (javac compiler would say "reference") instance variable (javac would say "non-static variable") from a static context (javac would say the same thing). This won't compile because during the static Fish[] myFish = new Fish[x]; there is no any Fish instance.
You can change your code to:
static int min = 8;
static int max = 12;
static int x = min + (int)(Math.random() * ((max-min) + 1));
This will make non-static variable x static.
Here's the official explanation of static variables (officials prefer to call them class variables).

Related

How can I properly initialize a variable created in a separate method, to be used in another method?

I have made two methods that take user input and should return two separate variables, that I want to call in a third method. However, I don't understand fully how to "link" the variables into the third method. It's also necessary that I keep all three methods separate, the calculate method, askLen and askWid.
I've tried a few things like declaring the integers in different places, using final int, or long, double, etc.
public static void main (String[] p)
{
askLen();
askWid();
calculate();
System.exit(0);
}
public static int askLen ()
{
final int len;
Scanner scanner = new Scanner(System.in);
System.out.println("What is the length of the room (in cm)?");
len = Integer.parseInt(scanner.nextLine());
final long l=len;
return len;
}
public static int askWid ()
{
final int wid;
Scanner scanner = new Scanner(System.in);
System.out.println("What is the width of the room (in cm)?");
wid = Integer.parseInt(scanner.nextLine());
final long w=wid;
return wid;
}
public static int calculate ()
{
final int len;
final long l;
final int wid;
final long w;
long area = (l * w) / 10000;
System.out.println("The area is " + area + "m^2");
double wastage = (area * 1.10) / 100;
System.out.println("The extra you need for wastage is " + wastage + "m^2");
double areaTotal = area + wastage;
System.out.println("The total flooring area to order is: " + areaTotal + "m^2");
return 1;
}
My expected result is that it correctly takes the user's integer inputs and does the arithmetic that I have coded, returning a final result of the strings above with the correct calculated answers.
The error messages I'm getting during compiling are:
flooring.java:46: error: variable l might not have been initialized
long area = (l * w) / 10000;
^
flooring.java:46: error: variable w might not have been initialized
long area = (l * w) / 10000;
^
2 errors
Why not just pass the variables to the methods? Something like:
public static void main (String[] p)
{
int length = askLen();
int width = askWid();
calculate(length, width);
System.exit(0);
}
public static int askLen ()
{
final int len;
Scanner scanner = new Scanner(System.in);
System.out.println("What is the length of the room (in cm)?");
len = Integer.parseInt(scanner.nextLine());
final long l=len;
return len;
}
public static int askWid ()
{
final int wid;
Scanner scanner = new Scanner(System.in);
System.out.println("What is the width of the room (in cm)?");
wid = Integer.parseInt(scanner.nextLine());
final long w=wid;
return wid;
}
public static void calculate (int len, int wid)
{
long area = (len * wid) / 10000;
System.out.println("The area is " + area + "m^2");
double wastage = (area * 1.10) / 100;
System.out.println("The extra you need for wastage is " + wastage + "m^2");
double areaTotal = area + wastage;
System.out.println("The total flooring area to order is: " + areaTotal + "m^2");
}
Also, in calculate() the variables l and w are never set to anything which is giving you the error. By passing in the variables you don't need to set/use l or w and can instead use the variables passed in the parenthesis wid and len. You also don't need a return type or return for calculate() unless you need to store the value in a variable from where you call the method.

Not getting right output for natural log formula

I'm trying to get my program to out the first 500 values for this formula: -12*ln(1-x) where x is the return of double next(). I don't know what I'm doing wrong because I can't get the right output. The random number uses this formula x(i+1) = (a * x(i) + c) mod k
public class myRnd {
// Linear values for x(i+1) = (a * x(i) + c) % k
final static int a = 7893;
final static int c = 3517;
final static int k = 8192;
// Current value for returning
int x;
int y;
int z;
public myRnd() {
// Constructor simply sets value to half of k
x = (125*k) /1024;
//y = (125*k) /1024;
}
double next() {
// Calculate next value in sequence
x = (a * x + c) % k;
// Return its 0 to 1 value
return (double)x / k;
}
public static void main(String[] args) {
int situation;
double sec_answer;
// Create a new myRnd instance
myRnd r = new myRnd();
// Output 53 random numbers from it
for (int i = 0; i < 53; i++) {
System.out.println (r.next());
}
System.out.println("random variable");
for(int b = 0; b < 500; b++){
sec_answer = (-12)*Math.log(1- r.next());
System.out.println(sec_answer);
}
}
}
I suppose these are the first 5 values you're expecting from your program in each loop!
0.9302978515625
0.270263671875
0.6204833984375
0.90478515625
0.8985595703125
random variable
31.962289651479345
3.78086405322487
11.626283246646423
28.21943313114782
27.45940262908609
In your main method you have only one instance of the class:
// Create a new myRnd instance
myRnd r = new myRnd();
This initialization is propagated to both for loops.
Simple Solution: Add another instance / initialization of myRnd for the second for loop, as an example you could reuse the same variable as r = new myRnd(); before the second loop.

Implementing Random Int in Java

I am using Blue J for reference.
What I need to do is after defining 2 constants, MIN = 60 and MAX = 180, which I already did, I am supposed to define the processtime as a random integer between 60 and 240, instead of the constant 120.
Problem is that I am unsure how to do that.
Here is the class, TicketCounter, in which that is supposed to be implemented in.
public class TicketCounter
{
final static int PROCESS = 120;
final static int MAX_CASHIERS = 10;
final static int NUM_CUSTOMERS = 200;
final static int ARR_TIME = 20;
final static int MIN = 60;
final static int MAX = 180;
public static void main ( String[] args)
{
Customer customer;
LinkedQueue<Customer> customerQueue = new LinkedQueue<Customer>();
int[] cashierTime = new int[MAX_CASHIERS];
int totalTime, averageTime, departs;
System.out.printf("%-25.30s %-30.30s%n", "Number of Cashiers", "Average Time (in seconds)");
/** process the simulation for various number of cashiers */
for (int cashiers=0; cashiers < MAX_CASHIERS; cashiers++)
{
/** set each cashiers time to zero initially*/
for (int count=0; count < cashiers; count++)
cashierTime[count] = 0;
/** load customer queue */
for (int count=1; count <= NUM_CUSTOMERS; count++)
customerQueue.enqueue(new Customer(count*ARR_TIME));
totalTime = 0;
/** process all customers in the queue */
while (!(customerQueue.isEmpty()))
{
for (int count=0; count <= cashiers; count++)
{
if (!(customerQueue.isEmpty()))
{
customer = customerQueue.dequeue();
if (customer.getArrivalTime() > cashierTime[count])
departs = customer.getArrivalTime() + PROCESS;
else
departs = cashierTime[count] + PROCESS;
customer.setDepartureTime (departs);
cashierTime[count] = departs;
totalTime += customer.totalTime();
}
}
}
/** output results for this simulation */
averageTime = totalTime / NUM_CUSTOMERS;
System.out.printf("%10s %30s%n", (cashiers+1), averageTime);
}
}
}
Thank you in advance!
I'm not fully sure if I understand what you're looking for, but what I am certain of is that you want to randomize an integer. This can easily be done by the Random class.
What I'm not sure about is whether you want to randomize a number between 60-120 (MIN-MAX) or 60-280. Whether the case it should look something like this.
Random r = new Random();
int randomInt = r.nextInt(MAX - MIN + 1) + MIN;
This code will now result the variable to be an integer between MIN and MAX, now you can easily replace those with constants or set values to them for nice and understandable code.
For further information of what the code exactly does, I would recommend you again, to take a look at the Random class, I find it very useful in many cases.
If you have MIN and MAX, and can use Random you might do -
Random random = new Random();
int MIN = 60;
int MAX = 180;
int val = random.nextInt(MAX + 1) + MIN;
Which will generate a random value between 60 inclusive and 240 inclusive. Random.nextInt(int) which (per the Javadoc),
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive).

Reusing variable from a different class?

This is probably quite simple, but i just dont know how to do it?
How do i reuse this from a class file:
int randomNum = 5 + (int)(Math.random() * ((10 - 5) + 1));
To then use the same result that this procures in another class file?
My CityWall Class (The Class containing the int i want to use.)
public class CityWalls extends Thing {
int randomNum = 5 + (int)(Math.random() * ((10 - 5) + 1));
public CityWalls(City c, int st, int av, Direction d) {
super(c, st ,av ,d);
int oddIncrement = 0;
if (randomNum % 2 == 0)
{
oddIncrement = 1;
}
for (int i = 0; i < randomNum; i++) {
new Wall(c, i+(7-randomNum/2), (7-randomNum/2), Direction.WEST);
new Wall(c, i+(7-randomNum/2), (7+randomNum/2) - oddIncrement, Direction.EAST);
new Wall(c, (7-randomNum/2), i+(7-randomNum/2), Direction.NORTH);
new Wall(c, (7+randomNum/2)-oddIncrement, i+(7-randomNum/2), Direction.SOUTH);
}
}
public int getRandomNum() {
return randomNum;
}
}
Here is my World Class (The Class where i want to reuse the variable).
public class World {
public static void main (String[] args) {
int height = 0, width = 0, top = 5, left = 5, thingCount = 20;
World b = new World();
Random rand = new Random();
// int RandomNumber = rand.nextInt(9);
CityWalls cw = new CityWalls(Gothenburg, 5 , 5, Direction.NORTH);
int RandomNumber = cw.getRandomNum();
height = (int)(Math.random() * 0.5) + RandomNumber; // I want to use the variable here.
width = (int)(Math.random() * 0.5) + RandomNumber; // And here to replace the RandomNumber. then it should be correct.
City Gothenburg = new City(16,16);
Thing[] things = ThingSpawnCity(Gothenburg, width, height, top, left, thingCount);
RobotFinder terminator = new RobotFinder(Gothenburg, 7, 7, Direction.NORTH, 0);
terminator.run();
}
public static Thing[] ThingSpawnCity(City Gothenburg, int width, int height, int top, int left, int objects){
Thing things[] = new Thing[objects];
int avenue = 0, street = 0;
for (int i = 0; i < objects; i++){
avenue = (int)(Math.random() * width) + left;
street = (int)(Math.random() * height) + top;
things[i] = new Thing(Gothenburg, street, avenue);
}
return things;
}
}
You need a reference to an instance of the class you want to use. You need need to access the field you want to use in that class. e.g.
class A {
int randomNum = 5 + (int)(Math.random() * ((10 - 5) + 1));
}
class B {
public void printNum(B b) {
System.out.println("Random Num " + b.randomNum);
}
}
public static void main(String... ignored) {
A a = new A();
B b = new B();
b.printNum(a);
}
Have a read about encapsulation and getters and setters, and you could do it like this:
int randomNum = 5 + (int)(Math.random() * ((10 - 5) + 1));
MySuperOtherClass other = new MySuperOtherClass();
other.setX(randomNum);
// now you can get it back with other.getX();
Add a getter for it in your class and make it public
public int getRandomNum() {
return randomNum;
}
EDIT
Class containing your random number:
public class ClassHavingARandomNumner {
int randomNum = 5 + (int)(Math.random() * ((10 - 5) + 1));
public int getRandomNum() {
return randomNum;
}
}
Another class that wants to access the random number
public class ClassWantingARandomNumber {
public static void main(String[] args) {
// create an instance of the class containing the random number
ClassHavingARandomNumner c = new ClassHavingARandomNumner();
// call the getter method to retrieve the random number
System.out.println(c.getRandomNum());
}
}
EDIT 2
first move
int randomNum = 5 + (int)(Math.random() * ((10 - 5) + 1));
outside of the constructor the make randomNumber a member variable of the class CiytWalls
Second, add the getter to CityWalls
Then in main assign the result of the constructor call to a local variable
CityWalls cw = new CityWalls(Gothenburg, 5 , 5, Direction.NORTH);
after that you can acces the random number of the CityWalls object you have created using:
int rn = cw.getRandomNumber();
You can do so by making member variable randomNum as static variable of class CityWalls. And use that variable to your World class. By doing so you will get the same value as specified in CityWalls class. But you actually want to reuse or I would say use the variable with the same name & don't want to allocate memory for it or any other reason you find it useful for your case then you should extend CityWalls class to your World class.
Hope this clarified your doubt.

how to assign random number with range to 2D array dimensions

In main, assign 2 random numbers (ints between 3 and 10) for the first dimension and the second dimension
I had this but the Math.random() method doesn;t work
import java.lang.Math;
public class Homework2 {
public static void main(String[] args){
double doubMatrix1[][] = (int) (Math.random()*(10-3+1)+3);
double doubMatrix2[][];
double doubMatrix3[][];
}
}
The problem in your code is that you are trying to initialize a matrix of double with an int
Types must be equals!
Here are your code fixed.
import java.lang.Math;
public class Homework2 {
public static void main(String[] args){
int d1 = (int) (Math.random()*(10-3+1)+3);
int d2 = (int) (Math.random()*(10-3+1)+3);
double doubMatrix1[][] = new double[d1][d2];
double doubMatrix2[][];
double doubMatrix3[][];
}
}
hope this help
To create a multidimensional array in Java, use new <type>[dim1][dim2], as in the following code:
Random rand = new Random();
int r1 = rand.nextInt(8) + 3;
int r2 = rand.nextInt(8) + 3;
double doubMatrix[][] = new double[r1][r2];
Math.random() returns fraction between 0.0 and 1.0. So with (int) (Math.random()*(10-3+1)+3) you are getting only one random number between 3 and 10 inclusive. But you are assigning it to double doubMatrix1[][]. So probably you are calling constructor in wrong way. You are supposed to generate two distinct random number r1, r2 according to the method taught by your teacher then call constructor like double doubMatrix1[][] = double[r1][r2]
check this out, this might be helpful:
// DMA of 2D array in C++
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int x = 3, y = 3;
int **ptr = new int *[x];
for(int i = 0; i<y; i++)
{
ptr[i] = new int[y];
}
srand(time(0));
for(int j = 0; j<x; j++)
{
for(int k = 0; k<y; k++)
{
int a = rand()%5;
ptr[j][k] = a;
cout<<ptr[j][k]<<" ";
}
cout<<endl;
}
}
we used a pointer and deal it just like 2D array here, use % for limit

Categories

Resources