2

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?

5 Answers 5

12

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>
Sign up to request clarification or add additional context in comments.

1 Comment

If you are satisfied, please accept the answer by clicking the checkmark to the side of the question. =)
3

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
}

1 Comment

Or Double.parseDouble(conductorSize) if a double is required/preferred.
0

It looks like what you're trying to do might better be expressed in this way:

conCsa = Double.parseDouble(conductorSize);

1 Comment

Dammit, my vote limit for the day is over. I wanna upvote this answer!
0

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.

Comments

0

When you have cable sizes which are constants, you need to use Enums , which will help you in reducing no of if condition comparisons.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.