Creating an Array with random numbers with a specific object reference - java

For each of the 100 elements of the calc, instantiate a Claclal object with
randomly generated numbers. Use the Random class along with the .nextDouble() method
for this.
I have already created the 100 elements but i cant add any numbers to the array. When i try and add any random numbers i get an error saying that it is requires a claclal but its found an int.
public class Claclal {
private static Claclal[] calc;
public static void main(String[] args) {
Random r = new Random();
calc = new Claclal[100];
for (int i = 0; i <calc.length; i++) {
calc[i] = new Claclal();
calc[i] = (int)(Math.random());
}
the error that i am getting is on the last line.
I cant change the reference to int because its supposed to be a claclal reference. What do i need to change to get the code to work?

You have an array of Clacal type, not int type. You have 2 options
1st) Create a property in Clacal that is the double.
Example:
public class Claclal {
private static Claclal[] calc;
private final double number;
public Clacal(double number){
this.number=number;
}
public static void main(String[] args) {
Random r = new Random();
calc = new Claclal[100];
for (int i = 0; i <calc.length; i++) {
calc[i] = new Claclal(r.nextDouble());
}
}
2nd) Make a double array
public class Claclal {
private static double[] calc;
public static void main(String[] args) {
Random r = new Random();
calc = new Claclal[100];
for (int i = 0; i <calc.length; i++) {
calc[i] = r.nextDouble();
}
}

calc[i] = (int)(Math.random());
That is not allowed since array type is Claclal, and you are trying to insert integer.
You need to take a field in Claclal class and add to that.
Claclal c= new Claclal();
c.setRandomNumber((int)(r.nextDouble()));
calc[i] = c;
Then your code turns
public class Claclal {
private static Claclal[] calc;
private int randomNumber;
public static void main(String[] args) {
Random r = new Random();
calc = new Claclal[100];
for (int i = 0; i < calc.length; i++) {
Claclal c = new Claclal();
c.setRandomNumber((int) (r.nextDouble()));
calc[i] = c;
}
}
public int getRandomNumber() {
return randomNumber;
}
public void setRandomNumber(int randomNumber) {
this.randomNumber = randomNumber;
}
}
More over you are using Math.random() and you want to use r.nextDouble()

You are trying to assign an int value as an element of the Claclal array.
You should add a field to the Claclal class to store a double value in each object. In your main method, use the Random object that you have instantiated to pass a new random double value to the constructor of each new instance of Claclal in the array.
import java.util.Random;
public class Claclal {
// the double field to store a value
private double value;
public Claclal(double value) {
this.value = value;
}
// getter
public double getValue() {
return this.value;
}
// setter
public void setValue(double value) {
this.value = value;
}
public static void main(String[] args) {
Random r = new Random();
Claclal[] calc = new Clalcal[100];
for (int i = 0; i < calc.length; i++) {
// add new Claclal object with a random double value
calc = new Claclal(r.nextDouble());
}
}
}

You are getting the error because the claclal class doesnot have any attribute.
Add an attribute in claclal as shown below:
import java.util.Random;
public class Claclal {
private static Claclal[] calc;
int value;
public Claclal( int value) {
this.value = value;
}
public static void main(String[] args) {
Random r = new Random();
calc = new Claclal[100];
for (int i = 0; i < calc.length; i++) {
calc[i] = new Claclal(r.nextInt());
System.out.println(""+calc[i].value);
}
}
}

Related

array initialized in one class but contents not accessible in another

i have a javafx application and it has two classes in it, namely "Client" and "Interface_Client_Impl". i have defined an int array in "Client" class and a function that initializes that array. when i tried to access the array contents at index i from Interface_Client_Impl, it always returns 0. Interface_Client_Impl class is accessed remotely and im able to get the values of variables but not the array. where am i going wrong. -_-
this is what i have.
public class Client extends Application
{
public int size = 4;
public int array[] = new int[size];
public int min = 1;
public int max = 99;
public static void main(String[] args) throws Exception
{
launch(args);
}
#Override
public void start(Stage primaryStage) throws NotBoundException, RemoteException
{
initialize_arr();
//other codes
}
public void initialize_arr()
{
Random rand = new Random();
for(int i = 0; i < size; i++)
{//initialize with random values
int val = rand.nextInt(max - min + 1) + min;
array[i] = val;
}
}
}
//another class
public class Interface_Client_Impl extends UnicastRemoteObject implements Interface_Client
{
public Client client = new Client();
#Override
public int exchange(int val)
{
Random rand = new Random();
int pos = rand.nextInt(client.size);
int return_val = client.array[pos];
client.array[pos] = val;
return return_val;
}
}
You have just created the instance for Client in class Interface_Client_Impl
You need to invoke the array initialization of client instance. You can do via following two ways
By invoking public method client.start(primaryStage)
or
by invoking public method client.initialize_arr()

Is it possible in java to get multiple inputs in a single line??

I am trying to get multiple inputs in a single code of line..
for example in c++, we could have it like -
int a,b,c;
cin>>a>>b>>c;
is it possible in java also??
You can use an array for this purpose, like:
public static void main(String[] args) {
int[] values = new int[3];
Scanner in = new Scanner(System.in);
for(int i = 0; i < values.length; i++) {
values[i] = in.nextInt();
}
System.out.println(Arrays.toString(values));
}
UPDATE 2
In java 8 the above solution can have a shorter version:
Scanner in = new Scanner(System.in);
Integer[] inputs = Stream.generate(in::nextInt).limit(3).toArray(Integer[]::new);
UPDATE 1
There is another way, which is closer to cin:
public class ChainScanner {
private Scanner scanner;
public ChainScanner(Scanner scanner) {
this.scanner = scanner;
}
public ChainScanner readIntTo(Consumer<Integer> consumer) {
consumer.accept(scanner.nextInt());
return this;
}
public ChainScanner readStringTo(Consumer<String> consumer) {
consumer.accept(scanner.next());
return this;
}
}
public class Wrapper {
private int a;
private int b;
private String c;
public void setA(int a) {
this.a = a;
} /* ... */
}
public static void main(String[] args) {
ChainScanner cs = new ChainScanner(new Scanner(System.in));
Wrapper wrapper = new Wrapper();
cs.readIntTo(wrapper::setA).readIntTo(wrapper::setB).readStringTo(wrapper::setC);
System.out.println(wrapper);
}

Trouble Creating An Array Of Objects in Java

This is my sticking point: I need to create an array of Chair objects with default woodType. I am able to declare the array itself, but obviously all the values are null. When I try to instantiate each Chair object in the array, I get errors. I'm not sure what I am doing wrong when trying to instantiate, please help.
public class PAssign3 {
public static void main(String[] args) {
TableSet set1 = new TableSet();
TableSet set2 = new TableSet(5, 7, 4);
// Chair chr1 = new Chair();//this works properly, setting wood as Oak
// Chair chr2 = new Chair("Pine");//works
}
}
class TableSet {
Table table = new Table();
private int numOfChairs = 2;
//creates an array that can hold "numOfChairs" references to same num of
//chair objects; does not instantiate chair objects!!!
Chair[] chairArr = new Chair[numOfChairs];
//instantiate each chair object for length of array
//this loop does not work; Error: illegal start of type
for (int i = 0; i < numOfChairs.length; i++) {
chairArr[i] = new Chair();
}
public TableSet() {
}
public TableSet(double width, double length, int numOfChairs) {
table = new Table(width, length);
this.numOfChairs = numOfChairs;
chairArr = new Chair[numOfChairs];
//this loop also does not work; Error: int cannot be dereferenced
for (int i = 0; i < numOfChairs.length; i++) {
chairArr[i] = new Chair();
}
}
public void setNumOfChairs(int numOfChairs) {
this.numOfChairs = numOfChairs;
}
public int getNumOfChairs() {
return numOfChairs;
}
public String getChairWoodType() {
return chairArr[0].getWoodType();
}
}
class Table {
private double width = 6;
private double length = 4;
public Table() {
}
public Table(double width, double length) {
this.width = width;
this.length = length;
}
public void setWidth(double width) {
this.width = (width < 0) ? 0 : width;
}
public void setLength(double length) {
this.length = (length < 0) ? 0 : width;
}
public double getWidth() {
return width;
}
public double getLength() {
return length;
}
}
class Chair {
private String woodType = "Oak";
public Chair() {
}
public Chair(String woodType) {
this.woodType = woodType;
}
public void setWoodType(String woodType) {
this.woodType = woodType;
}
public String getWoodType() {
return woodType;
}
}
int is a simple type in Java and does not have any methods or fields. Just omit this .length and the error is gone. It seems to me it already stores the actual number of chairs (2).

How to access an array from another class

I want to operate on the array called "players" that is declared in the main method. I want to use "players" in my class called "Glucksspielthread"
I know that I can't access "players" because it is declared in the main method and is not visible for other classes.
How can I solve this problem? Here is my code:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Glucksspieltest {
public static void main(String[] args) {
int numPlayers = Integer.parseInt(args[0]);
int threadSize = Integer.parseInt(args[1]);
ExecutorService es = Executors.newFixedThreadPool(threadSize);
Glucksspielthread[] players = new Glucksspielthread[numPlayers];
for (int i = 0; i < numPlayers; i++) {
players[i] = new Glucksspielthread(i);
es.execute(players[i]);
}
}
}
class Thinker {
public static void think(int Millisekunden) {
try {
Thread.sleep(Millisekunden);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void randomThink(int minMillisekunden, int maxMillisekunden) {
System.out.println("test");
}
}
class Glucksspielthread implements Runnable {
public int playerNumber;
Glucksspielthread(int number) {
playerNumber = number;
}
#Override
public void run() {
for (int i = 0; i <= playerNumber; i++) {
// here, I want to operate on array called "players" that is declared in the main method
}
}
}
Just for your test purpose make your players variable static and public in the Glucksspieltest class, like this:
public class Glucksspieltest {
public static Glucksspielthread[] players;
Then acces it in the Glucksspielthread class like this:
for (int i = 0; i <= playerNumber; i++) {
// here, I want to operate on array called "players" that is declared in the main method
Glucksspieltest.players
}
Add a method to class Glucksspieltest, and make the players array global:
public class Glucksspieltest {
private static Glucksspielthread[] players;
public static Glucksspielthread[] getPlayers(){
return players;
}
public static void main(String[] args) {
int numPlayers = Integer.parseInt(args[0]);
int threadSize = Integer.parseInt(args[1]);
ExecutorService es = Executors.newFixedThreadPool(threadSize);
players = new Glucksspielthread[numPlayers];
for (int i = 0; i < numPlayers; i++) {
players[i] = new Glucksspielthread(i);
es.execute(players[i]);
}
}
}
This way you can get the array by calling the getPlayers() method.
(Note that, it would be adviced to add a constructor to initialize and fill the players array, and separate the player management from the main method as well.)
Make players as private global referance variable
public class Glucksspieltest {
//Make a Global reference variable players
private static Glucksspielthread[] players;
// Make a getter Method to get players
public static Glucksspielthread[] getPlayers(){
return players;
}
public static void main(String[] args) {
int numPlayers = Integer.parseInt(args[0]);
int threadSize = Integer.parseInt(args[1]);
ExecutorService es = Executors.newFixedThreadPool(threadSize);
players = new Glucksspielthread[numPlayers];
for (int i = 0; i < numPlayers; i++) {
players[i] = new Glucksspielthread(i);
es.execute(players[i]);
}
}
}
And access it by Glucksspieltest.getPlayers();
class Glucksspielthread implements Runnable {
public int playerNumber;
private static Glucksspielthread[] players;
Glucksspielthread(int number) {
playerNumber = number;
}
#Override
public void run() {
for (int i = 0; i <= playerNumber; i++) {
// here, I want to operate on array called "players" that is declared in the main method
players= Glucksspieltest.getPlayers(); // play with players
}
}
}

Constructor for array of variable size

I want to code a constructor for an array of size x with x being a parameter speciified in main().
My class:
public class CharA
{
private char[] stack;
private int n = 0;
public void CharA (int max)
{
this.stack = new char[max];
this.n = max;
}
My main():
public class CharTest
{
public static void main (String args)
{
CharA stack1 = new CharA(100);
}
}
The error:
CharTest.java:5: cannot find symbol
symbol : constructor CharA(int)
location: class CharA
CharA stack1 = new CharA(100);
^
There are several examples here where the same thing is done with an int array. Why doesn't it work for this char array?
remove void in your "constructor":
public CharA (int max) {
// ...
}
Replace public void CharA (int max) with public CharA (int max), because constructors don't have a return type.
The constructor method should not have a return type in its definition:
public CharA(int max) {...}

Categories