sorry if my question is stupid, but i have problem with calling variable from method with few arguments.
public void onAccelSensorChanged(long axisX, long axisY, long axisZ) {
accelx = axisX;
accely = axisY;
accelz = axisZ;
accelText.setText("\nACCELEROMETER: \nX: " + axisX + "nm/s^2 || Y: " + axisY + "nm/s^2 || Z: " + axisZ +"nm/s^2");
}
Ok, and i need call variable accelx, accely, accelz, but each of them elsewhere in the code.. Is there any simple method to do this in java?
I need make something like that:
case 0xf41f1000: /*pongiGetAccelerateX()*/
//i need call accelX in below 'pongiGetAccelerateX method, but now it returned 0
result = spnNative.pongiGetAccelerateX(accelX);
break;
------EDIT----
My class :
public class SPN_API implements onAccelSensorChanged{
private SPN_native spnNative;
public long accelX, accelY, accelZ;
public SPN_API() {
spnNative = new SPN_native();
}
public byte[] invoke_command(int commandId, int argsImageLength, int actualNrOfArgs) {
byte[] result = null;
switch(commandId){
case 0xf41f1000: /*pongiGetAccelerateX()*/
//i need call accelX in below 'pongiGetAccelerateX method, but now it returned 0
result = spnNative.pongiGetAccelerateX(accelX);
break;
case 0xf51f1000: /*pongiGetAccelerateY()*/
result = spnNative.pongiGetAccelerateX(accelY);
break;
case 0xf61f1000: /*pongiGetAccelerateZ()*/
result = spnNative.pongiGetAccelerateX(accelZ);
break;
}
return result;
}
#Override
public void onAccelSensorChanged(long axisX, long axisY, long axisZ) {
accelx = axisX;
accely = axisY;
accelz = axisZ;
}
}
You can either return the value and pass it into the other function as an argument or you can use a global variable in the class scope so that it can be accessed and changed from anywhere.
Make sure your class implements SensorEventListener.
Then remove onAccelSensorChange and copy this in.
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
accelX = event.values[0];
accelY = event.values[1];
accelZ = event.values[2];
}
}
Related
I cannot understand the meaning of the code. Can you give me a help to translate the code into Java?
private var framePeriodMs: Long = 0
var frameRate: Float = Float.MAX_VALUE
set(value) {
this.framePeriodMs = (1000 / value).toLong()
log.info("framePeriodMs: $framePeriodMs")
field = value
}
Thank you very much...
This should be about right (though my Java's rusty):
private long framePeriodMs = 0;
private float frameRate = Float.MAX_VALUE;
public float getFrameRate() {
return frameRate;
}
public void setFrameRate(float newFrameRate) {
this.framePeriodMs = (long)(1000 / newFrameRate);
log.info("framePeriodMs: " + framePeriodMs);
this.frameRate = newFrameRate;
}
The value coming into the set(...) { ... } function is just like a parameter into a Java setter.
As you can see that I am trying to increment the variable 'c' when the accelerometer z-axis value greater than 12. But I can do it at one time, it will change the value 0 to 1 after executing the program. But I want to collect how many times the z-axis value becomes more than 12.
#Override
public void onSensorChanged (SensorEvent event) {
textView.setText(event.values[0] + "");
textView1.setText(event.values[1] + "");
textView2.setText(event.values[2] + "");
String s = new String();
s = textView2.getText().toString().trim();
Float t = Float.parseFloat(s);
int c = 0;
if (t > 11) {
c++;
txt.setText(Integer.toString(c));
}
}
int counter = 0;
#Override
public void onSensorChanged (SensorEvent event) {
textView.setText(event.values[0] + "");
textView1.setText(event.values[1] + "");
textView2.setText(event.values[2] + "");
String s = new String();
s = textView2.getText().toString().trim();
Float t = Float.parseFloat(s);
int c = 0; // ???
if (t > 11) {
c++;
counter++;
txt.setText(Integer.toString(c));
System.out.println("I need to learn how to use global
variables.\n
also the thing has been greater than \"12\"
"+counter" times."
);
}
}
Also maybe using more meaningful variable names other than "textView#" would make it less of a pain for people to figure out what you're trying to do.
You can define the variable c as a field member like below:
public class MainActivity {
private int c = 0;
(...)
#Override
public void onSensorChanged (SensorEvent event) {
textView.setText(event.values[0] + "");
textView1.setText(event.values[1] + "");
textView2.setText(event.values[2] + "");
String s = new String();
s = textView2.getText().toString().trim();
Float t = Float.parseFloat(s);
if (t > 11) {
c++;
txt.setText(Integer.toString(c));
}
}
}
I have to write a program to convert between linear units in, ft, mi, mm, cm, m, km. I know there are easier and better ways to do this. I think we'ere just trying to fully understand if else if statements. But this is what I have so far. I'm just trying to figure out if I am on the right track. I've tried to write out some pseudocode but it just seems like a lot going on so I find it a bit overwhelming. Next I'm going to add a method to convert form in or mm to whatever is selected by the user.
When I test the program i get this: UnitConversion#76c5a2f7 (EDIT: THIS ISSUE WAS FIXED)
Ok I made the suggested changes and that allowed the first part of the program to run properly. I have now added my second method to convert from in/mm to the other measurements.. I was having issues but I figured it out.
Here is my main method;
public class LinearConversion
{
public static void main(String[] args)
{
UnitConversion newConvert = new UnitConversion("km", "m", 100);
System.out.println(newConvert);
}
}
Any suggestions? What am I missing or not understanding about doing this sort of program?
public class UnitConversion
{
private String input;
private String output;
private double value;
private double temp;
private double in, ft, mi, mm, cm, m, km;
private final double inch_feet = 12;
private final double inch_miles = 63360;
private final double inch_millimeters = 25.4;
private final double inch_centimeters = 2.54;
private final double inch_meters = 0.0254;
private final double inch_kilometers = 0.0000254;
private final double millimeters_inch = 0.0393701;
private final double millimeters_feet = 0.00328084;
private final double millimeters_miles = 0.000000622;
private final double millimeter_centimeters = 10;
private final double millimeter_meters = 1000;
private final double millimeter_kilometers = 1000000;
public UnitConversion(String in, String out, double val)
{
input = in;
output = out;
value = val;
}
public String toString()
{
if (input.equals("mi"))
{
in = value * inch_miles;
input = "in";
}
else if (input.equals("ft"))
{
in = value * inch_feet;
input = "in";
}
else
{
in = value;
input = "in";
}
if (input.equals("km"))
{
mm = value * millimeter_kilometers;
input = "mm";
}
else if (input.equals("m"))
{
mm = value * millimeter_meters;
input = "mm";
}
else if (input.equals("cm"))
{
mm = value * millimeter_centimeters;
input = "mm";
}
else
{
mm = value;
input = "mm";
}
return value + input + " " + output;
}
public double getUnit()
{
if (input.equals("in"))
{
if (output.equals("ft"))
{
ft = in * inch_feet;
System.out.println(ft + "ft");
}
else if (output.equals("mi"))
{
mi = in * inch_miles;
System.out.println(mi + "mi");
}
else if (output.equals("mm"))
{
mm = in * inch_millimeters;
System.out.println(mm + "mm");
}
else if (output.equals("cm"))
{
cm = in * inch_centimeters;
System.out.println(cm + "cm");
}
else if (output.equals("m"))
{
m = in * inch_meters;
System.out.println(m + "m");
}
else if (output.equals("km"))
{
km = in * inch_kilometers;
System.out.println(km + "km");
}
else
{
System.out.println(in + "in");
}
}
else
{
if (output.equals("cm"))
{
cm = mm * millimeter_centimeters;
System.out.println(cm + "cm");
}
else if (output.equals("m"))
{
m = mm * millimeter_meters;
System.out.println(m + "m");
}
else if (output.equals("km"))
{
km = mm * millimeter_kilometers;
System.out.println(km + "km");
}
else if (output.equals("in"))
{
in = mm * millimeters_inch;
System.out.println(in + "in");
}
else if (output.equals("ft"))
{
ft = mm * millimeters_feet;
System.out.println(ft + "ft");
}
else if (output.equals("mi"))
{
mi = mm * millimeters_miles;
System.out.println(mi + "mi");
}
else
{
System.out.println(mm + "mm");
}
}
}
Basically, you need/want to give a String argument to System.out.println in order to display it.
Thus, when you use System.out.println with an Object (that is not a String) as the argument, Java actually outputs the result of the toString method on that object.
If you haven't overridden it, the Object class' implementation of toString is used: this is what gives you your current output: UnitConversion#76c5a2f7.
To learn more about how is this default toString implementation generating that String, you can refer to the javadoc entry for Object#toString.
Base on your output, and your provided code, yes! Rename String getInput() to String toString() and your current main() will work, or change your current main()
System.out.println(newConvert.getInput()); // <-- added .getInput()
I have a list of similar classes that are all children of the same abstract class. I also have an array of Booleans that should correspond to which class should be used.
For example, I have a bunch of classes, named with the following convention:
boolean[] classesOn = new boolean[4];
abstract class myClass {}
class myClass1 extends myClass { public void myClass1(float x, float y) ...}
class myClass2 extends myClass {}
class myClass3 extends myClass {}
class myClass4 extends myClass {}
...
The idea is to only use the classes that have the corresponding boolean on in classesOn. To do this I use a for loop that iterates through classesOn and checks which are true. Right now I have the following code:
for (int i = 0; i < classesOn.length; i++) {
if (classesOn[i]) {
switch (i) {
case 0: c = new myClass1(x, y); break;
case 1: c = new myClass2(x, y); break;
...
Now this is extremely inefficient and as I add new extensions of myClass I need to add a new case. I'd like to be able to just say if (classesOn[i]) { c = new "myClass" + (i + 1) ();} to create an instance of that particular class.
How can I do this?
(btw, these are just examples, and the actual implementation of each class varies greatly)
The use I'm currently working on is actually in Processing, where there are multiple color schemes each represented in a class. But I'm curious how to do this for all types of classes in the future as well.
The exact code that I'm working on right now looks like this - (but I'm interested in the answer in general)
abstract class Scheme {
float red,blue,green,x,y;
String description;
public void mousespot(){
this.x = mouseX;
this.y = mouseY;
return;
}
public float getRed(){
return this.red;
}
public float getBlue(){
return this.blue;
}
public float getGreen(){
return this.green;
}
public String getDescription(){
fill(255,255,255);
textSize(32);
return this.description;
}
}
class Scheme1 extends Scheme {
public Scheme1(float x, float y) {
this.description = "Green-Yellow-GW-Turqouise";
this.red = map(x, 0, width, 0, 255);
this.blue = map(y, 0, height, 0, 255);
this.green = 255 * (float) dist(width/2, height/2, x, y) / (x / y);
}
}
class Scheme2 extends Scheme {
public Scheme2(float x, float y) {
this.description = "Red-Yellow-Peach-Magenta";
this.green = map(x, 0, width, 0, 255);
this.blue = map(y, 0, height, 0, 255);
this.red = 255 * (float) dist(width/2, height/2, x, y) / (x / y);
}
}
and in the mouseDragged() method:
for (i = 0; i < colorschemesOn.length;i++) {
if (colorschemesOn[i]) {
switch(i) {
case 0:
public Scheme selectedScheme = new Scheme1(mouseX,mouseY);
break;
case 1:
public Scheme selectedScheme = new Scheme2(mouseX,mouseY);
break;
case 2:
public Scheme selectedScheme = new Scheme3(mouseX,mouseY);
break;
case 3:
public Scheme selectedScheme = new Scheme4(mouseX,mouseY);
break;
case 4:
public Scheme selectedScheme = new Scheme5(mouseX,mouseY);
break;
case 5:
public Scheme selectedScheme = new Scheme6(mouseX,mouseY);
break;
case 6:
public Scheme selectedScheme = new Scheme7(mouseX,mouseY);
break;
case 7:
public Scheme selectedScheme = new Scheme8(mouseX,mouseY);
break;
case 8:
public Scheme selectedScheme = new Scheme9(mouseX,mouseY);
break;
case 9:
public Scheme selectedScheme = new Scheme10(mouseX,mouseY);
break;
case 10:
public Scheme selectedScheme = new Scheme11(mouseX,mouseY);
break;
case 11:
public Scheme selectedScheme = new Scheme12(mouseX,mouseY);
break;
default:
public Scheme selectedScheme = new Scheme1(mouseX,mouseY);
break;
}
}
}
Do not rely on naming conventions, create an array rather:
Class<? extends myClass>[] classes = new Class<? extends myClass>[] {
myClass1.class, myClass2.class, myClass3.class, myClass4.class
};
boolean[] classesOn = new boolean[classes.length];
Then you can instantiate them with reflection:
if (classesOn[i]) { myClass c = classes[i].getConstructor().newInstance(); }
If your constructor takes arguments:
myClass c;
if (i < classesOn.lenght && classesOn[i]) {
c = classes[i]
.getConstructor(float.class, float.class)
.newInstance(mouseX, mouseY);
} else {
c = new myClass1(mouseX, mouseY);
}
You can use reflection
if (classesOn[i]) { c = Class.forName("myClass" + (i + 1)).newInstance(); }
This is rarely a good idea, and there is usually a better way to structure your classes/code which means you don't need it.
A more elegant way might be to use the Reflections library. (not to be confused with the built in one)
It supports querying classes by such things as annotations or interfaces. You could get it to find all the sub classes of myClass no matter what they are called or JAR they are in.
If you constructor takes two arguments you can pass the two arguments to it.
if (classesOn[i]) {
c = Class.forName("myClass" + (i + 1))
.getConstructor(float.class, float.class)
.newInstance(mouseX, mouseY);
}
I find the PowerScript's CHOOSE CASE statement very useful, as it make so that the code is more clearly than a lot of ifs and else ifs.
Here a example of how it works, from the above link:
CHOOSE CASE weight
CASE IS < 16
Postage=Weight*0.30
Method="USPS"
CASE 16 to 48
Postage=4.50
Method="UPS"
CASE ELSE
Postage=25.00
Method="FedEx"
END CHOOSE
a CASE 5 to 11 is the same as CASE 5, 6, 7, 8, 9, 10, 11
Note that the CHOOSE CASE is not equivalent to java's switch
In Java, you can use multiple case statements, but there isn't a nice way to specify an expression as the case qualifier, just literals:
switch(weight) {
case 1:
case 2:
case 3:
postage = weight * 0.30;
method = "USPS";
break;
case 4:
case 5:
case 6:
postage = 4.5;
method = "UPS";
break;
default:
postage = 25.0;
method = "FedEx";
break;
}
To get nice ranges, stick with if/else:
if(weight > 0 && weight <= 3) {
postage = weight * 0.30;
method = "USPS";
}
else if(weight > 3 && weight <= 6) {
postage = 4.5;
method = "UPS";
}
else {
postage = 25.0;
method = "FedEx";
}
If your objective is cleaning up the decision point, you could encapsulate the code that decides what case applies separately from the code that uses that decision, as in:
enum WeightClass { LOW, MEDIUM, HIGH };
public WeightClass determineWeightClass(int weight)
{
return (weight < 16)
? WeightClass.LOW
: (weight <= 48
? WeightClass.MEDIUM
: WeightClass.HIGH);
}
And at the decision point:
switch(determineWeightClass(weight))
{
case LOW:
...
break;
case MEDIUM:
...
break;
case HIGH:
...
break;
}
Not exactly the same. If you want to implement such fragment in Java, you have to use if-else[-if] statement.
Basically, it should look like this:
if (weight < 16) {
//something
} else if (weight >= 16 && weight <= 48) {
//something else
} else {
//some other thing
}
Hope it works for you. :)
If there are only 3 cases, a series of if/else is fine. If you have many conditions, you could use a Navigable map and couple it with an enum for a nice and slick design:
public class Test1 {
public static void main(String[] args) {
printDelivery(0);
printDelivery(5);
printDelivery(16);
printDelivery(48);
printDelivery(50);
}
private static void printDelivery(int weight) {
Delivery d = Delivery.getDelivery(weight);
System.out.println("Weight: " + weight + " => $" + d.getPostage(weight) + " with " + d.getMethod());
}
static enum Delivery {
LOW_WEIGHT(15) {
public double getPostage(int weight) { return 0.3 * weight; }
public String getMethod() { return "USPS"; }
}, MEDIUM_WEIGHT(47) {
public double getPostage(int weight) { return 4.5; }
public String getMethod() { return "UPS"; }
}, HIGH_WEIGHT(Integer.MAX_VALUE){
public double getPostage(int weight) { return 25.0; }
public String getMethod() { return "FedEx"; }
};
private static final NavigableMap<Integer, Delivery> deliveries = new TreeMap<> ();
static {
for (Delivery e : values()) {
deliveries.put(e.maxWeight, e);
}
}
private final int maxWeight;
Delivery(int maxWeight) {
this.maxWeight = maxWeight;
}
public static Delivery getDelivery(int weight) {
return deliveries.ceilingEntry(weight).getValue();
}
abstract double getPostage(int weight);
abstract String getMethod();
}
}
No. You would have to use a series of if-elseif-else statements.