user1869638
user1869638

Reputation: 33

Issue with the "if" statement

I'm taking a CS course and this code is giving me problems.

         while (statScan.hasNext()){

        currentStat = statScan.next();
        if (currentStat =  h);
        {       
            hStat++;
        }
        System.out.println("" + currentStat);

Look at the "if" statement. Java says "cannot convert string to boolean" and from my understanding boolean is a true/false sorta thing so what Java isn't understanding is how to evaluate and compare the strings. How do I force it to do so?

Upvotes: 3

Views: 145

Answers (4)

Goran Štuc
Goran Štuc

Reputation: 581

the problem is that you assign it instead of ask if it's equal (assign '=', equals '==')
this is the solution for that line: also if it's strings use .equals()

if (currentStat.equals(h))

Upvotes: 4

Ben Kelly
Ben Kelly

Reputation: 1344

A few problems here:

if (currentStat =  h);

First, you have a semicolon at the end which will cause the if-statement to not function as you want. It is basically conditionally executing an empty statement. The following block of code (which you intended to be conditional) will always be run. Remove the semicolon to avoid this.

Also, you only have = instead of ==. This means you are assigning the value of h to currentStat. This is a classic, classic typo. As @YogendraSingh mentioned in the other answer, you should use the equals() method to perform comparisons on strings in Java. Otherwise you are only comparing to see if the two items are exactly the same object. Do detect when the same string text is held in two different objects you need to use equals().

So change this line to:

if (h.equals(currentStat))

Upvotes: 1

Jack
Jack

Reputation: 133669

The = operator in Java is intended as an assignment operator, so when you write x = y you don't mean is x equal to y but assign value of y to x.

The comparison operator is the == operator but this will compare either primitive types (int, char, float, etc) either references to objects that is not the usual behavior you need. For anything that is not a primitive type you should consider using the method inherited by Object which is boolean equals(Object o). To understand exactly why it is so, take a look here or here.

Upvotes: 1

Yogendra Singh
Yogendra Singh

Reputation: 34397

Assuming h is a string, use equals method for string comparison as:

      if(currentStat.equals(h))

Currently you are using assignment operator =, which assigns the string value of h to currentStat.

When you change the operator to comparison operator == then it will compare the object instance equality and not the value, which I think you don't want/

Upvotes: 0

Related Questions