translate kotlin set value into java - java

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.

Related

Cannot resolve symbol myLatitude

new to programming i know i'm doing something that's probably really obviously wrong to do with passing or using the wrong variables but i just can't work out what.
Here is my code:
public class CameraViewActivity extends Activity implements
SurfaceHolder.Callback, OnLocationChangedListener, OnAzimuthChangedListener {
private double mAzimuthReal = 0;
private double mAzimuthTheoretical = 0;
private static double AZIMUTH_ACCURACY = 5;
private double mMyLatitude = 0;
private double mMyLongitude = 0;
private List<Double> calculateAzimuthAccuracy(double azimuth) {
double minAngle = azimuth - AZIMUTH_ACCURACY;
double maxAngle = azimuth + AZIMUTH_ACCURACY;
List<Double> minMax = new ArrayList<Double>();
#Override
public void onAzimuthChanged(float azimuthChangedFrom, float azimuthChangedTo) {
mAzimuthReal = azimuthChangedTo;
mAzimuthTheoretical = calculateTheoreticalAzimuth();
pointerIcon = (ImageView) findViewById(R.id.icon);
double minAngle = calculateAzimuthAccuracy(mAzimuthTheoretical).get(0);
double maxAngle = calculateAzimuthAccuracy(mAzimuthTheoretical).get(1);
if (isBetween(minAngle, maxAngle, mAzimuthReaal) {
pointerIcon.setVisibility(View.VISIBLE);
}
else {
pointerIcon.setVisibility(View.INVISIBLE);
}
updateDescription();
}
Thanks for reading
Use
isRange(mMyLatitude, mMyLongitude, mPoi.getPoiLatitude(), mPoi.getPoiLongitude)
instead of
isRange(MyLatitude, MyLongitude, MpoiLatitude, MpoiLongitude)
FYI, its better to use small letter for naming variable.
In this function you need to pass as paramters either two locations and use their coordinates in the function inRange or you pass four coordinates and use them.
public void onAzimuthChanged(float azimuthChangedFrom, float azimuthChangedTo) {
mAzimuthReal = azimuthChangedTo;
mAzimuthTheoretical = calculateTheoreticalAzimuth();
pointerIcon = (ImageView) findViewById(R.id.icon);
double minAngle = calculateAzimuthAccuracy(mAzimuthTheoretical).get(0);
double maxAngle = calculateAzimuthAccuracy(mAzimuthTheoretical).get(1);
if (isBetween(minAngle, maxAngle, mAzimuthReal) && isRange(MyLatitude, MyLongitude, MpoiLatitude, MpoiLongitude)) {
pointerIcon.setVisibility(View.VISIBLE);
}
else {
pointerIcon.setVisibility(View.INVISIBLE);
}
updateDescription();
}
This has no meaning
isRange(MyLatitude, MyLongitude, MpoiLatitude, MpoiLongitude);
One more thing, adapt a professional naming criteria. Giving your attributes names that start with capital letters is quite MEH.

How to make this code better?

I wrote some code like this in Java:
//...
if(dsLen>=4){
ds.longitude = buff.readInt();
dsLen-=4;
}
else{
return ds;
}
if(dsLen>=4){
ds.latitude = buff.readInt();
dsLen-=4;
}
else{
return ds;
}
if(dsLen>=2){
ds.velocity = buff.readShort();
dsLen-=2;
}
else{
return ds;
}
//...
It seems ugly. How can I improved it?
As far as I know, Java does not support reference value via arguments. That's really a puzzle to me.
You can define a class like this:
class MaybeReader {
BufferType buff;
int dsLen;
boolean failed = false;
// Add a constructor to populate buff and dsLen appropriately.
boolean failed(long obj) {
return failed;
}
int maybeReadInt(int defaultValue) {
if (dsLen >= 4) {
dsLen -= 4;
return buff.readInt();
} else {
failed = true;
return defaultValue;
}
}
short maybeReadShort(short defaultValue) {
if (dsLen >= 2) {
dsLen -= 2;
return buff.readShort();
} else {
failed = true;
return defaultValue;
}
}
}
Then you can invoke it reasonably compactly like this:
MaybeReader m = new MaybeReader(...);
if (m.failed(ds.longitude = m.maybeReadInt(ds.longitude))
|| m.failed(ds.latitude = m.maybeReadInt(ds.latitude))
|| m.failed(ds.velocity = m.maybeReadShort(ds.velocity)) {
return ds;
}
This works as follows:
You need to pass in the current value of the field, in order that you can write it back in the case that you can't read the value from the buffer.
The maybeRead* methods will read from the buffer if there is enough data; otherwise, they return the default value, and set the instance into a "failed" state.
The result of the maybeRead* is then passed back into failed. The argument isn't actually used, it is just to use the assignment as an boolean expression rather than a statement. This involves a widening cast to long; you can add overloads for specific primitive types, if you want.
The fast-break evaluation of the || means that execution will stop as soon as one of the maybeRead* calls fail.
However: I don't think that this is especially intuitive to read, however; in particular, expressions with multiple side effects (the assignments) are considered hard to read. I would just accept that Java can be a verbose language, and write code that is obvious at a glance.
If the value of dsLen is irrelevant after a return statement was executed, your code can be simplified as
if (dsLen >= 4) {
ds.longitude = buff.readInt();
}
if (dsLen >= 8) {
ds.latitude = buff.readInt();
}
if (dsLen >= 10) {
ds.velocity = buff.readShort();
}
return ds;
The rest of the code could be improved as well. It looks like longitude, latitute and velocity are public fields of ds. It's probably a better idea to encapsulate them by making them private instead.
If you really need to change the state of ds in other parts of the code, use a setter.
If you don't need to change the state of ds, consider making the fields final, assign them in the constructor and return a new object of ds' type in the method in your question,
public final class WhateverType {
private final int longitude;
private final int latitude;
private final short velocity;
public WhateverType(int longitude, int latitude, short velocity) {
this.longitude = longitude;
this.latitude = latitude;
this.velocity = velocity;
}
// rest of the code
}
then the code in your method could look like:
int longitude = -1; // or whatever default values you're assigning
int latitude = -1;
short velocity = -1;
if (dsLen >= 4) {
longitude = buff.readInt();
}
if (dsLen >= 8) {
latitude = buff.readInt();
}
if (dsLen >= 10) {
velocity = buff.readShort();
}
return new WhateverType(longitude, latitude, velocity);

Generate Data Points for Graph from an equation

I don't want to solve an equation and my question is not about Graphs and Trees Data Structures. I am trying to generate Data Points for graph from an equation given by user. I want efficient algorithm, easy to use and easy to maintain data structures. I have two solutions in mind
1: This is trivial and I have seen in many Applications.
String expr = "2*x+3*x";
Evaluator evaluator = new Evaluator();//I have this class
for (int i = start; i < end; i += step)
{
evaluator.setConstant("x", i);
double ans = evaluator.evaluate(expr);
}
This is very slow because each time every step is repeated like tokenzing, verifying, conversion to RPN, preparing stacks and queues and at last result calculation. The possible solution to this problem is somehow caching all stacks and queues but after that a comparison would be required between current expression and previous expression to use last stored state.
2: Currently I am developing second solution. The purpose of this is efficiency and would be used in Symbolic calculation in future.
So far my implementation
Variable.java
import java.text.DecimalFormat;
public class Variable
{
private final double pow;
private final double coefficient;
private final String symbol;
public Variable(String symbol)
{
this.symbol = symbol;
this.pow = 1.0;
this.coefficient = 1.0;
}
public Variable(String symbol, double coefficient, double pow)throws IllegalArgumentException
{
if (coefficient == 0.0)throw new IllegalArgumentException("trying to create variable with coefficient 0");
if (pow == 0.0)throw new IllegalArgumentException("trying to create variable with exponent 0");
this.symbol = symbol;
this.pow = pow;
this.coefficient = coefficient;
}
public final String getSymbol()
{
return this.symbol;
}
public final double getPow()
{
return this.pow;
}
public final double getCoefficient()
{
return this.coefficient;
}
#Override
public String toString()
{
StringBuilder builder = new StringBuilder();
DecimalFormat decimalFormat = new DecimalFormat("#.############");
if (coefficient != 1.0)builder.append(decimalFormat.format(this.coefficient));
builder.append(this.symbol);
if (this.pow != 1.0)builder.append("^").append(decimalFormat.format(this.pow));
return builder.toString();
}
/*
* Stub Method
* Generate some unique hash code
* such that chances of key collision
* become less and easy to identify
* variables with same power and same
* symbol*/
#Override
public int hashCode()
{
return 0;
}
}
Equation.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
public class Equation
{
private final ArrayList<Boolean> operations;
private final HashMap<String, Variable> variableHashMap;
private int typesOfVariables;
public Equation(Variable variable)
{
this.variableHashMap = new HashMap<>();
this.operations = new ArrayList<>();
this.typesOfVariables = 1;
this.variableHashMap.put(variable.getSymbol(), variable);
}
/*Stub Method*/
public void addVariable(Variable variable, boolean multiply)
{
/*
* Currently not covering many cases
* 1: Add two variables which have same name
* and same pow.
* 2: variable which are wrapped inside functions e.g sin(x)
* and many other.*/
if (multiply && variableHashMap.containsKey(variable.getSymbol()))
{
Variable var = variableHashMap.get(variable.getSymbol());
Variable newVar = new Variable(var.getSymbol(), var.getCoefficient() * variable.getCoefficient(), var.getPow() + variable.getPow());
/*
* Collision chances for variables with same name but
* with different powers*/
this.variableHashMap.replace(var.getSymbol(), newVar);
}
else
{
++this.typesOfVariables;
this.variableHashMap.put(variable.getSymbol(), variable);
}
this.operations.add(multiply);
}
/*Stub Method
*Value for every variable at any point will be different*/
public double solveFor(double x)
{
if (typesOfVariables > 1)throw new IllegalArgumentException("provide values for all variables");
Iterator<HashMap.Entry<String, Variable>> entryIterator = this.variableHashMap.entrySet().iterator();
Variable var;
double ans = 0.0;
if (entryIterator.hasNext())
{
var = entryIterator.next().getValue();
ans = var.getCoefficient() * Math.pow(x, var.getPow());
}
for (int i = 0; entryIterator.hasNext(); i++)
{
var = entryIterator.next().getValue();
if (this.operations.get(i))ans *= var.getCoefficient() * Math.pow(x, var.getPow());
else ans += var.getCoefficient() * Math.pow(x, var.getPow());
}
return ans;
}
#Override
public String toString()
{
StringBuilder builder = new StringBuilder();
Iterator<HashMap.Entry<String, Variable>> entryIterator = this.variableHashMap.entrySet().iterator();
if (entryIterator.hasNext())builder.append(entryIterator.next().getValue().toString());
Variable var;
for (int i = 0; entryIterator.hasNext(); i++)
{
var = entryIterator.next().getValue();
if (this.operations.get(i))builder.append("*").append(var.toString());
else builder.append(var.toString());
}
return builder.toString();
}
}
Main.java
class Main
{
public static void main(String[] args)
{
try
{
long t1 = System.nanoTime();
Variable variable = new Variable("x");
Variable variable1 = new Variable("x", -2.0, 1.0);
Variable variable2 = new Variable("x", 3.0, 4.0);
Equation equation = new Equation(variable);
equation.addVariable(variable1, true);//2x+x
equation.addVariable(variable2, true);
for (int i = 0; i < 1000000; i++)equation.solveFor(i);//Calculate Million Data Points
long t2 = System.nanoTime();
System.out.println((t2-t1)/1000/1000);
System.out.println(equation.toString());
}
catch (Exception e)
{
System.out.println("Error: " + e.getMessage());
}
}
}
Am I going in right direction?
Is there any commonly used Algorithm for this problem?
My main goal is efficiency, code cleanness and code maintainability.
Note: I am not native English speaker so please ignore any grammatical mistake.
Thanks.
I do not see any problem with your first code. Yes may be at every step your code "repeat like tokenzing, verifying, conversion to RPN, preparing stacks and queues and at last result calculation", but in the end all of this is just linear number of steps. So I fail to see how it can make it really slow.
One of the biggest screens I have seen was 2560x1440 pixels, which means that most of the time you would need less than 2500 points to draw your graph there.
If you point is code cleanness and code maintainability, then most probably a code consisting of 5 lines is better than the code consisting of 200.

Java: How to call one argument from methods with multiple arguments

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

Converting Units using if statements?

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

Categories

Resources