简体   繁体   中英

a bug with a condition code (if)

I was checking my code by eclipse that I got one of my conditions doesn't work correctly! this is the code: for example in here the first = "44" and last = "54" so first Sub and last Sub are 4, 5.

String firstSub = first.substring(0,1);
String firstSub = last.substring(0,1);
System.out.println(firstSub + "..." + lastSub);

if (firstSub.equals(lastSub))
    System.out.println("row");

So by the output that printed I got first Sub and last Sub are not equal but string "row" printed!

What is the problem? original codes:

System.out.println(ebteda+ "--" +enteha);
ebtedaSub = ebteda.substring(0,1);
entehaSub = enteha.substring(0,1);
System.out.println(ebtedaSub + "_" + entehaSub);

if(ebtedaSub.equals(entehaSub));
{
System.out.println(ebteda.substring(0,1)+enteha.substring(0,1));
hamsatr(ebteda,enteha);
}

Remove the ; following the if

if(ebtedaSub.equals(entehaSub));
{
    System.out.println(ebteda.substring(0,1)+enteha.substring(0,1));
    hamsatr(ebteda,enteha);
}

So it should be

if(ebtedaSub.equals(entehaSub))
{
    System.out.println(ebteda.substring(0,1)+enteha.substring(0,1));
    hamsatr(ebteda,enteha);
}

Assuming that firstSub refers to first.substring() and lastSub refers to last.substring() , and any compilation issues aside, your code produces

firstSub = "4"
lastSub = "5"

which of course are not equal.

You can print out firstSub and lastSub to verify, but it is clear in the Javadoc for substring(int, int) .

More specifically, the last character picked by the substring(int, int) method is not the one with the same index supplied, but the previous one, so substring(0, 1) will start from character with index 0 and end with character with index 1-1 = 0 , ie it will produce a string that only consists of the first character of the original string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM