Call method from another file as string in Java - 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.

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

How can I create instance in Java when the factory method is default(non-static)

class X {
private int i;
private X(){}
X factory(int v){ // d
X r = new X();
r.i = v;
return r;
}
}
How can we create an instance of X using this part of codes? I can think of reflection but I think that is too complex. Is there any simpler way to figure out this problem? (Do not add static to factory method and do not delete the private key word of the constructor method).
You may use a builder inner class like this (main method added for testing purpose, of course you could call X.Builder from outside this class) :
class X {
private int i;
private X() {
}
public static class Builder {
public static X factory(final int v) { // d
X r = new X();
r.i = v;
return r;
}
}
public static void main(String[] args) {
X myX = X.Builder.factory(42);
}
}

troubles with creating objects in java

Hello So I have a entire class called tractor with different data's stored in it but now I'm suppose to create an object call tractor with a zero parameter constructor but This is the code I have so far and its giving em errors
First off this my Tractor Class which is in a different file:
import java.util.Scanner;
class Tractor
{
private int RentalRate;
private int RentalDays;
private int VehicleID;
private int RentalProfit;
public void setRentalRate(int r)
{
Scanner input = new Scanner(System.in);
System.out.println("What's the Rental Rate?");
int num = input.nextInt();
num = r;
if(r<0 || r >1000)
RentalRate = r;
RentalRate= 1;
}
public int getRentalRate()
{
return RentalRate;
}
public void setVehicleID(int v)
{
Scanner input = new Scanner(System.in);
System.out.println("What's the vehicleID?");
int num1 = input.nextInt();
num1 = v;
if(v<0)
VehicleID = v;
VehicleID = 1;
}
public int getVehicleID()
{
return VehicleID;
}
public void setRentalDays(int d)
{
Scanner input = new Scanner(System.in);
System.out.println("How many rental days?");
int num2 = input.nextInt();
num2 = d;
if(d<0)
RentalDays = d;
RentalDays = 1;
}
public int getRentalDays()
{
return RentalDays;
}
public String toString()
{
String str;
str = "RentalDays:" + RentalDays +"\nRenalRate:" + RentalRate + "\nVehicleID " + VehicleID;
return str;
}
public void RentalProfit(int RentalRate, int RentalDays)
{
RentalProfit = RentalRate * RentalDays;
}
}
import java.util.Scanner;
public class testTractor
{
public static void main(String[] args)
{
public tractor()
{
this.RentalDays = d;
this.RentalRate = r;
this.VehicleID = v;
}
}
}
The error is :
testTractor.java:7: error: illegal start of expression
public tractor()
^
testTractor.java:7: error: ';' expected
public tractor()
^
2 errors
You have compilation errors. You need to first declare the Tractor class then add the constructor inside it. One way to do is declare in a separate file. Also in Java unless you had defined d you couldnt have assigned it. Maybe you wanted to assign the day as a String look in the examples I provide below.
You need to to first create a file call Tractor.java and then define variables there. For example contents of Tractor.java:
public class Tractor {
String rentaldays,someOtherValue;
public Tractor(){
rentaldays ="monday";
someOtherValue="value";
}
//or
public Tractor(String rentalDays){
this.rentaldays = rentalDays;
someOtherValue = "asf";
}
}
Then in your main method You can do Tractor trac = new Tractor(); or Tractor trac = new Tractor("tuesday"); also after that you can print the rentaldays of trac using System.out.println(trac.rentaldays);
From the looks of it you will probably be making a tractor rental system. In that case, rentalDays may be an array of Strings. And then you would have an array of Tractor objects to store in the rental system. You can look at these terms and keywords to point you in the right direction.
You are defining it wrong, define your methods inside class then call them in main() method.
class Test{
public void greeting(){
System.out.print("hello to JAVA..");
}
public static void main(String[] args){
Test testObj = new Test();
testObj.greeting();
}
}
you use an illegal of java syntax, if you already have class tractor in your project. for calling it to in other class, try below code
public class TestTractor(){
Tractor objTractor;
public static void main(String[] args){
//create new tractor object with no parameter
objTractor = new Tractor();
//create new tractor object with parameter
objTractor = new Tractor(parameter here);
//do some action of object here
...........
}
}
//This is just a sample
in your tractor class add below code
public tractor()
{
this.RentalDays = d;
this.RentalRate = r;
this.VehicleID = v;
}
And keep your TestTractor class as
public class TestTractor(){
public static void main(String[] args){
Tractor objTractor = new Tractor();
// objTractor.yourMethodName
}
}

storing passed variables into array automatically - java

I am having trouble storing a variable passed from a class into another classe's array.
I am passing a double that has been scanned in class A, to class B where I wish for the doubles to be stored in a double array, as long as the scanner in class A hasNext().
My code in class B, resembles something like this:
// I can't seem to get the passed doubles to be stored as individual elements of the array
public class B {
public final static int MAX_SIZE = 200;
public int i;
public double passedOne;
public void store() {
double[] storedOneVars = storedOneVars[MAX_SIZE]; // create a system to store variables in the array
for (i = 0; i < MAX_SIZE; i++) {
storedOneVars[i] = passedOne;
}
for (double s : storedOneVars) {
System.out.println(s);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new NumberRow().store();
}
}
I am open to suggestions :D
My Java is a little rusty, but I don't see where you are passing variable references to your class B. To add a reference to a value you can either create a constructor which excepts a parameter or pass the parameter into your store() method.
Also, you are instantiating your array incorrectly.
double[] storedOneVars = storedOneVars[MAX_SIZE];
should be
double[] storedOneVars = new double[MAX_SIZE];
You are also instantiating NumberRow but not assigning to a reference variable. Even worse is there is no NumberRow class. There is a class B. so is should be something like this:
B myB = new B();
Here is an example:
class B {
private double[] myDoubleArray;
public double[] getMyDoubleArray() {
return myDoubleArray;
}
public void setMyDoubleArray(double[] myDoubleArray) {
this.myDoubleArray = myDoubleArray;
}
public B(double[] dArray){
setMyDoubleArray(dArray);
}
public void store() {
for (double s : getMyDoubleArray()) {
System.out.println(s);
}
}
}
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
double[] myd = new double[]{1,2,3};
B myB = new B(myd);
myB.store();
}
}

java - access incremented static variable from another class

I have a static variable and updating it's value in class. But when i access this variable from another class , it shows unupdated value.
CLASS A
public static int postID = 1;
public static String Creator()
{
String message = "POST id="+postID;
return message;
}
void updatePostID()
{
postID++; //this function is being called each 10 seconds
}
#Override
public void start() {
handler.post(show);
}
Handler handler = new Handler();
private final Runnable show = new Runnable(){
public void run(){
...
updatePostID();
handler.postDelayed(this, 10000);
}
};
CLASS B
String message = A.Creator(); //this always prints postID as 1 all time
I need a global variable that i can access from each class and update its value. Waiting for your help (I am using this with a Android Service)
this is a tested code .
public class A {
public static int id = 0;
public static int increment(){
return A.id++;
}
}
public class B {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(A.increment());
}
}
}
class A
{
static int id=0;
//I am updating id in my function ,
{
id++;
}
}
public class StartingPoint {
public static void main(String... args){
A a = new A();
A b = new A();
System.out.println(A.id);
System.out.println(a.id);
}
}
You need to call work to execute id++;
class B {
public static void main(String... args){
A a = new A();
a.work(); // You need to call it to apply add operation
System.out.println(A.id); // Prints 1
}
}
And this is a sample class A:
class A {
static int id = 0;
public void work(){
id++;
}
}
Save class A in a file named A.java and class B in a file named B.java.
Then compile B. Since B creates an instance of class A, A will be compiled and you don't need to compile A separately-
javac B.java
After compilation, to execute/run-
java B
Sajal Dutta's answer explains it perfectly, but if you want to keep it ALL static (i.e. not create any objects of class A, you could modify the code slightly to this:
class A {
static int id = 0;
public static void work(){
id++;
}
}
Then:
class B {
public static void main(String[] args){
System.out.println(A.id);
A.work();
System.out.println(A.id);
}
}
This would produce:
0
1
Edit (with regard to your updated question)
Where are you specifying the update of the static int? From the code you've provided all you will do is print out the same int over and over as the method containing the increment process is never called.
Edit 2:
Try this:
Change:
handler.post(show);
to:
handler.postDelayed(show, 10000);

Categories