Reputation: 441
I have an array in containing numbers that represent cable sizes (1, 1.5, 2.5, etc), stored as strings.
In my program, the array is loaded into a spinner, which is working fine. However, when the item is selected and stored in a variable, I want to check what string was selected, and set another numerical variable to 2.5 so I can do a calculation later in the program.
I tried the following:
if (conductorSize = "1" ) {conCsa = 1;}
else if (conductorSize = "1.5") {conCsa = 1.5;}
conductorSize
being the variable holding the selected string, and conCsa
being the variable
set to a numerical variable for calculation.
The compiler says that I cannot convert a string to boolean. What's happening?
Upvotes: 2
Views: 1149
Reputation: 12585
When you have cable sizes which are constants, you need to use Enums , which will help you in reducing no of if condition comparisons.
Upvotes: 0
Reputation: 3009
In general you need to use the .equals() method. If performance is extremely important and you are comparing against string literals, take a look at String.intern(). It'll allow you to do super-fast == comparisons and avoid a full character-by-character scan as in .equals(). Performance would have to be really, really important though, to justify such a non-standard approach.
Upvotes: 0
Reputation: 10918
As Ed S. points out you are using the assignment operator. However since you are comparing a String
you need to use the equals
method.
if ("1".equals(conductorSize)) {conCsa = 1;}
else if ("1.5".equals(conductorSize)) {conCsa = 1.5;}
Alternatively, you could just create a new float
from your String
:
float conCsa;
try {
conCsa = Float.parseFloat(conductorSize);
}catch(NumberFormatException e){
conCsa = 0.0f; //set to a default value
}
Upvotes: 3
Reputation: 129832
It looks like what you're trying to do might better be expressed in this way:
conCsa = Double.parseDouble(conductorSize);
Upvotes: 0
Reputation: 3106
If you are doing string comparisons, use .equals() Example taken from here:
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT <<<<<<<<<<<<< Use this.
if (s > t) // ILLEGAL
if (s.compareTo(t) > 0) // CORRECT>
Upvotes: 12