array initialized in one class but contents not accessible in another - java

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()

Related

Trying to increment local variable from a separate method but not working. Confusion about Activation Stack/Record

public class Demo {
public static void main(String[] args){
Demo instance = new Demo();
instance.init();
}
public void init() {
int size = 0;
inc(size);
System.out.println(size);
}
public int inc(int size){
size++;
return size;
}
}
When I call the code above, the number zero is returned.
Even declaring size as a class attribute instead of a local variable does not solve the problem. I understand that when a method is complete, the corresponding record (containing local variable and such) is popped off of the activation stack. But, if the size variable is declared in the init() method, and then incremented and returned in a separate method (inc()), shouldn't size be equal to 1?
When incrementing you do not assign the value to anything, it increments it, but it does not store it anywhere so the value remains 0, try doing like this.
public class Demo
{
public static void main(String[] args)
{
Demo instance = new Demo();
instance.init();
}
public void init()
{
int size = 0;
size = inc(size);
System.out.println(size);
}
public int inc(int size)
{
size++;
return size;
}
}
or like this
public class Demo
{
public static void main(String[] args)
{
Demo instance = new Demo();
instance.init();
}
public void init()
{
int size = 0;
System.out.println(inc(size));
}
public int inc(int size)
{
size++;
return size;
}
}
size = inc(size);
will solve your problem, since you are not using a public scoped variable.
If you want to make this a bit elegant (at least I think this will be a bit more handy), then you need to declare a variable as a class variable.
I will illustrate this to you:
public class Demo {
int size; //global range variable
public static void main(String[] args){
Demo instance = new Demo();
instance.init();
}
public void init() {
this.size = 0;
inc();
System.out.println(this.size);
}
public void inc(){
this.size++; //will increment your variable evertime you call it
}
}

Call method from another file as string in Java

I have file ClassifierModule.java with following method:
public class ClassifierModule extends ReactContextBaseJavaModule implements BufferListener {
public int measureRatio(double[] means) {
return (int) (means[3] / means[1]) ;
}
}
I'm trying to call this method to create a String in another .java file like this:
public static void main(String[] args) {
int r = ClassifierModule.measureRatio(double[]);
}
The only result I get is an error:
error: '.class' expected:
int r = ClassifierModule.measureRatio(double[]);
^
What am I doing wrong?
Here is the fuul code of ClassifierModule.java -> https://drive.google.com/file/d/1M6UlRkGEduBxQIsuOz93HEMGPtI8NiB9/view?usp=sharing
public class ClassifierModule extends ReactContextBaseJavaModule implements BufferListener {
public int measureRatio(double[] means){
return (int) (means[3] / means[1]) ;
}
}
measureRatio is an instance method, so it can't be called through the class, but must be called through an instance of the class.
public static void main(String[] args) {
int r = ClassifierModule.measureRatio(double[]);
}
double[] is the type which you have to pass, but it's not a value the method can work with. Change it to something like:
public static void main(String[] args) {
double[] param = new double[5];
param[0] = 7; param[1] = 8; param[2] = 4;
param[3] = 3; param[4] = 4;
ClassifierModule module = new ClassifierModule();
int r = module.measureRatio(param);
}
As not mentioned, one could simply make the method static as it does not depend on any state, on any instance object of the class.
public static int measureRatio(double[] means){
return (int) (means[3] / means[1]) ;
}
However the class extends and implements things, probably providing some context for evaluation.
public class ClassifierModule extends ReactContextBaseJavaModule implements BufferListener {
public ClassifierModule (ReactApplicationContext reactContext) {
super(reactContext);
}
public int measureRatio(double[] means) {
// Maybe use: getReactApplicationContext()
return (int) (means[3] / means[1]) ;
}
}
Then one would need to do something like:
int r = new ClassifierModule(...).measureRatio(double[]);
You need to do simple modifications
Non static methods can not be called by class name.
BufferListener {
public static int measureRatio(double[] means) {
return (int) (means[3] / means[1]) ;
}
}
You are trying to pass a type in second code. Not a double array.
public static void main(String[] args) {
double[] array= new double[5];
array[0] = 1; array[1] = 2; array[2] = 3;
array[3] = 5; array[4] = 4;
int r = ClassifierModule.measureRatio(array);//array is a double array
}
You are calling the method like it was a method at class level.
You have to create an object of type ClassifierModule in order to be able to call the method, like this:
public static void main(String[] args) {
// create an object
ClassifierModule cm = new ClassifierModule();
// define a parameter to be passed
double[] values = {3.0, 4.0}; // this is just an example array!
// and call the method with that parameter
int r = cm.measureRatio(double[]);
}
As an alternative, you could make the method of the ClassifierModule a class method by making it static:
public class ClassifierModule extends ReactContextBaseJavaModule implements BufferListener {
// this is now a method at class level
public static int measureRatio(double[] means) {
return (int) (means[3] / means[1]) ;
}
}
public static void main(String[] args) {
// define a parameter to be passed
double[] values = {3.0, 4.0}; // this is just an example array!
int r = ClassifierModule.measureRatio(values);
}
It depends on your requirements what option you should choose.

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
}
}
}

NullPointerException when adding a new object to an array

I am trying to add a Play name and length for a Theatre Seat Management Program. I want to be able to add new plays that will be on show at the theatre. Currently I have the following for class Play and its subclasses LocalPlay and ForeignPlay
public class Play {
public String name;
public double length;
public Play(String name, double length){
this.name = name;
this.length = length;
}
public void printPlayList(){
System.out.print("name = " + this.name);
System.out.print("length - " + this.length);
}
}
class ForeignPlay extends Play{
public ForeignPlay(String name, double length){
super(name, length);
}
}
class LocalPlay extends Play{
public LocalPlay(String name, double length){
super(name, length);
}
}
For my Admin class (the class I wish to use the addPlay function within), I am trying to add new objects to the class by passing a String and double. This is my code:
public class Admin extends User{
private Play [] play;
private int size = 0;
public void addForeignPlay(String name, double length){
this.play[size] = new ForeignPlay(name,length);
this.size++;
}
public void addLocalPlay(String name, double length){
this.play[size] = new LocalPlay(name,length);
this.size++;
}
public void playDetails(){
for(int i = 0; i < this.size; i++)
this.play[i].printPlayList();
}
public static void main (String[] args){
Admin testAdmin = new Admin();
testAdmin.addLocalPlay("test", 125);
testAdmin.playDetails();
}
}
When attempting to run this, I would expect to have an output of 'Test' and 125.0. However, I am receiving the error message:
Exception in thread "main" java.lang.NullPointerException
at Admin.addLocalPlay(Admin.java:18)
at Admin.main(Admin.java:33)
Thank you kindly for any help you can provide
Replace private Play [] play; with private Play [] play = new Play[10];
Without initializing an array you cannot store any value in that array
Suggestion for your Admin class:
public class Admin extends User {
private ArrayList<Play> playList = new ArrayList<>();
public void addForeignPlay(String name, double length) {
this.playList.add(new ForeignPlay(name, length));
}
public void addLocalPlay(String name, double length) {
this.playList.add(new LocalPlay(name, length));
}
public void playDetails() {
for (int i = 0; i < playList.size(); i++) {
this.playList.get(i).printPlayList();
}
}
public static void main(String[] args) {
Admin testAdmin = new Admin();
testAdmin.addLocalPlay("test", 125);
testAdmin.playDetails();
}
}
In Java, arrays are not dynamic (the size is fixed and determined at his creation). If you want dynamic data structure, you should use an ArrayList for exemple.
You should initialise the play variable like
private Play [] play = new Play[100]
or use constructor
public Admin(Play[] play, int size) {
this.play = play;
this.size = size;
}

Creating an Array with random numbers with a specific object reference

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);
}
}
}

Categories