Cannot assign calculation to this value - java

I want a placeholder value to hold the answer to a calculation, however the compiler doesn't like it.
Here is my code..
float valueOne = Float.parseFloat(txtOne.getText());
float valueTwo = Float.parseFloat(txtTwo.getText());
float valueThree = Float.parseFloat(txtThree.getText());
float final = valueOne+valueTwo+valueThree; // this line is bringing errors
Would really appreciate it if you could help me out.

Your problem is that final is a reserved keyword in Java. You cannot use it as a variable name. Just rename your last variable to something like finalValue and it will compile fine.
float valueOne = Float.parseFloat(txtOne.getText());
float valueTwo = Float.parseFloat(txtTwo.getText());
float valueThree = Float.parseFloat(txtThree.getText());
float finalValue = valueOne+valueTwo+valueThree;
Here is a list of keywords in Java.

final is a keyword. Try changing your float final to another name like float finalAnswer

It is because you use the keyword final.
Change your name
float valueOne = Float.parseFloat(txtOne.getText());
float valueTwo = Float.parseFloat(txtTwo.getText());
float valueThree = Float.parseFloat(txtThree.getText());
float finalHolder = valueOne+valueTwo+valueThree; // No more errors

final is a reserved keyword in java you can not use it as variable name.

Related

convert a data string to float in Java

I have the problem that in my program I have 4 annotated combo boxes and 2 of them return a number but in String type, which I need to store in a floating type variable, My combo box is called combo2 and
jComboBox4, the 2 variables that you see are the ones in which I need to store the data but I need to convert them. I would appreciate your help. Greetings.
//My combobox is combo2 and jComboBox4
// I need save in this variables
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
int numeroextra1;
int numeroextra2;
}
You can convert string variable to float as following:
string s = "123.45";
float f = Float.parseFloat(s);
You can use following methods:
String s = "10.01";
Float fObject = Float.valueOf(s);//get Float object
float fNumber = Float.parseFloat(s);//get float number

Convert String to Float with Large Number

Im using MPandroid chart to inflate Pie Chart, with some String JSON return
i tried to cast String value with float.parseFloat("3584907054456.48")
but it had exponent value when i log it, something like this 3584907E12
i need to get float value 3584907054456.48
is it possible ?
List<String> dataStackedSalesVolume1;
List<String> dataStackedSalesVolume2;
float[] firstDataStacked = new float[counte];
float[] secondDataStacked = new float[counte];
int counte = merchantECommerceDataAll.getData().getMerchantECommerceTipekartuList().getMerchantECommerceTipeKartuData().get(1).getDataSalesVolume().size();
dataStackedSalesVolume1 = merchantECommerceDataAll.getData().getMerchantECommerceTipekartuList().getMerchantECommerceTipeKartuData().get(0).getDataSalesVolume();
dataStackedSalesVolume2 = merchantECommerceDataAll.getData().getMerchantECommerceTipekartuList().getMerchantECommerceTipeKartuData().get(1).getDataSalesVolume();
for (int i=0; i< counte; i++) {
firstDataStacked[i] = Float.parseFloat(dataStackedSalesVolume1.get(i));
secondDataStacked[i] = Float.parseFloat(dataStackedSalesVolume2.get(i));
}
i tried to get the string and put it into new list and then parse that list and put parsed value into float[]
but it the results is rounded, i need to get the full length of data without rounded
Edit - The BigDecimal value can be converted to float value by using the floatValue() method. (Example - float requiredValue = bigDecimalValue.floatValue();)
Do note however that this will result in a drop in precision.
BigDecimal bigDecimalValue = new BigDecimal("3584907054456.48");
System.out.println(bigDecimalValue); //3584907054456.48
float floatValue = bigDecimalValue.floatValue();
System.out.println(floatValue); //3.58490702E12
//Formatted better to show the drop in precision.
System.out.println(String.format("%.2f", floatValue)); //3584907018240.00
Don't use float, use BigDecimal instead.
Do note that you won't be directly able to use operators such as +,-,*,etc. You'll have to use the provided methods, refer to the official documentation or an article such GeeksForGeeks articles to help you get an initial hang of it.
Sample code -
List<String> dataStackedSalesVolume1;
List<String> dataStackedSalesVolume2;
BigDecimal[] firstDataStacked = new BigDecimal[counte];
BigDecimal[] secondDataStacked = new BigDecimal[counte];
int counte = merchantECommerceDataAll.getData().getMerchantECommerceTipekartuList().getMerchantECommerceTipeKartuData().get(1).getDataSalesVolume().size();
dataStackedSalesVolume1 = merchantECommerceDataAll.getData().getMerchantECommerceTipekartuList().getMerchantECommerceTipeKartuData().get(0).getDataSalesVolume();
dataStackedSalesVolume2 = merchantECommerceDataAll.getData().getMerchantECommerceTipekartuList().getMerchantECommerceTipeKartuData().get(1).getDataSalesVolume();
for (int i=0; i< counte; i++) {
firstDataStacked[i] = new BigDecimal(dataStackedSalesVolume1.get(i));
secondDataStacked[i] = new BigDecimal(dataStackedSalesVolume2.get(i));
}
You can use something like BigDecimal.valueOf(new Double("3584907054456.48")) from java.math
After this you can divide, compare your value and so on

Making a int with Math.random pick a new number when called

Right now my variables all are being rolled randomly but only once. How can I make it so that when the ints are called they roll a new number? All the stats are currently the same number. And everything is rolled only once.
int throwD4 = (int)(Math.random()*4+1);
int throwD6 = (int)(Math.random()*6+1);
int throwD8 = (int)(Math.random()*8+1);
int throwD10 = (int)(Math.random()*10+1);
int throwD12 = (int)(Math.random()*12+1);
int throwD20 = (int)(Math.random()*20+1);
int throwD100 = (int)(Math.random()*100+1);
int stat = (int)(throwD6 + throwD6 + throwD6);
String description = "A big strong dude with a cool longsword.";
String name = "Gladiator";
// stats
int STR = stat;
int DEX = stat;
int CON = stat;
int INT = stat;
int WIS = stat;
int CHA = stat;'
Yes, you will certainly find that if you calculate a formula and then store it in a variable, then the variable will keep its value unless the formula is re-calculated and stored again in the variable. Accessing a variable's value doesn't re-run the formula that created it; the variable is just a dumb number that doesn't remember the formula. The fact that variables don't change unless you change them will be mighty handy over the lifecycle of your program.
Consider creating a method that returns you a random number, and every time you want a random, call the method:
public int throwDice(int howManySides){
return (int)(Math.random()*(howManySides+1));
}
If you want more advice on how this might be used, add some contexts to your question as to how you're currently using e.g. throwD6
In essence, every time you think about writing throwD6, write throwDice(6) instead. For example:
//rolling a 6 kills the character
if(throwDice(6) == 6)
character.Kill();

Converting a pointer to an array in C++ to Java (OpenCV)

I'm in the process of converting a function in OpenCV which is in C++ to Java. Link.
I don't know too much about C++ and struggling to convert this part:
/// Set the ranges ( for B,G,R) )
float range[] = { 0, 256 } ; //the upper boundary is exclusive
const float* histRange = { range };
This is what I have so far:
//Set of ranges
float ranges[] = {0,256};
final float histRange = {ranges};
Edit:
Thanks for your help, I have managed to get it working. This question was in the context of OpenCV (Sorry if I didn't make it clear). Code:
//Set of ranges
float ranges[] = {0,256};
MatOfFloat histRange = new MatOfFloat(ranges);
Unless I am mistaken with my pointers today, the second line in the c++ code duplicates pointer of range, so they both point at the same pair of values. What you want in Java should be this:
float ranges[] = {0,256};
final float histRange[] = ranges;
Thanks for your help, I have managed to get it working. This question was in the context of OpenCV (Sorry if I didn't make it clear). Code:
//Set of ranges
float ranges[] = {0,256};
MatOfFloat histRange = new MatOfFloat(ranges);

What is the purpose of variable duplication in a method?

I see this [below] all over in the Android code (and some other code sources). What is its point or purpose?
class Foo {
int mBar = 1337;
static void main(String... args) {
System.out.println(isFubar());
}
boolean isFubar() {
int ret = mBar; // <--- Focus of attention
if (ret == 666)
return true;
else
return false;
}
}
It seems like a waste of time and resources. mBar clearly isn't being modified. There is no risk of it being modified (in the given context), so why would one duplicate the primitive just to preform a noninvasive check on it and return?
EDIT Specific example from the class CellLayout in the Android Source
public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, RectF dragRect) {
final boolean portrait = mPortrait; <--- Here it is
final int cellWidth = mCellWidth;
final int cellHeight = mCellHeight;
final int widthGap = mWidthGap;
final int heightGap = mHeightGap;
final int hStartPadding = portrait ? mShortAxisStartPadding : mLongAxisStartPadding;
final int vStartPadding = portrait ? mLongAxisStartPadding : mShortAxisStartPadding;
int width = cellHSpan * cellWidth + ((cellHSpan - 1) * widthGap);
int height = cellVSpan * cellHeight + ((cellVSpan - 1) * heightGap);
int x = hStartPadding + cellX * (cellWidth + widthGap);
int y = vStartPadding + cellY * (cellHeight + heightGap);
dragRect.set(x, y, x + width, y + height);
}
Perhaps for multi-threading. If the value of mPortrait changed between the following two lines you would have mixed results.
final int hStartPadding = mPortrait ? mShortAxisStartPadding : mLongAxisStartPadding;
final int vStartPadding = mPortrait ? mLongAxisStartPadding : mShortAxisStartPadding;
For example:
final int hStartPadding = true ? mShortAxisStartPadding : mLongAxisStartPadding;
// somehwere else: mPortraint = false
final int vStartPadding = false ? mLongAxisStartPadding : mShortAxisStartPadding;
A few ideas come to mind.
The expression needed to retrieve the class member variable might be really complicated (your example is not), so saving it in a local variable might be more readable.
It is possible that storing it in a local variable is more efficient, especially if the method has to access the value more than once. (Your example does not do this.)
Retrieving the value once gets its value at that moment in time, and not some later value that another thread may have modified in the meantime.
Storing it in a local variable makes it easy to examine with a debugger.
For your particular example, only reason (4) makes any sense.
I use it so i can modify the variable in recursion or loops and not mess with the original one. It also helps with passing the variables between classes and other methods.
Also, if it is changed while the method is running, the method will not mess up, it will continue with the variables it started with. I had this major problem while multi-threading my graphics printing and code. The code would change variables and weird stuff would happen on the screen.
I don't know about hardware or speed, but on the code side, it makes it very simple and flexible in many cases.

Categories