Christian Baker
Christian Baker

Reputation: 389

Java String Comparison is failing, using equals method

do
{
    System.out.println("Type another number to continue or type 'End' to end");
    end = scan.next();

    if("end".equals(end)==false||"End".equals(end)==false)
    {
        num2 = Integer.parseInt(end);   


        int j = 0;          
        while (j < num2)
        {
            System.out.println(name);
            j++;
        }

        if(j == 0)
        {
            num2 = 0;   
        }
    }   
} while("end".equals(end)==false||"End".equals(end)==false);    

The String comparison keeps failing. When you type 'End' or 'end' it tries to parse it into an integer and returns an error. Idk why this is happening.

Upvotes: 2

Views: 354

Answers (3)

tckmn
tckmn

Reputation: 59273

if("end".equals(end)==false||"End".equals(end)==false)

Think about it: that would always be true. If the user typed end, then the first case would be true and the second false.

You could fix it by using && instead, but a better method would be:

if(!("end".equalsIgnoreCase(end)))

Also, so you don't have to check the condition twice, you could just use

while (true) {
    System.out.println("Type another number to continue or type 'End' to end");
    end = scan.next();
    if ("end".equalsIgnoreCase(end)) break;
    // now do your stuff
    num2 = Integer.parseInt(end);
    // ...
}

Upvotes: 3

rgettman
rgettman

Reputation: 178243

This line will always be true:

if("end".equals(end)==false||"End".equals(end)==false)

because at least one of them will always be true. You want it not to equal "end" and not to equal "End". Replace || with &&:

if("end".equals(end)==false && "End".equals(end)==false)

There's no need to compare the value with false; just use the ! negation operator:

if(!("end".equals(end)) && !("End".equals(end)))

You will need to make a similar change to the condition at the end of your do-while loop.

Upvotes: 2

Prabhaker A
Prabhaker A

Reputation: 8473

You are parsing end to int num2 by the statement num2 = Integer.parseInt(end);.
That will you NumberFormatException

Upvotes: 0

Related Questions