简体   繁体   中英

Char variable doesn't change value first time around when char = ' '?

         for(i=0, j=word.length()-1; i<=j; i++, j--)
         {
            char first = word.charAt(i);
            char last = word.charAt(j);

            while(first<'a' || first>'z')
            {
               first = word.charAt(i++);
            }
            while(last<'a' || last>'z')
            {
               last = word.charAt(j--);
               //last = word.charAt(j);
            }
            System.out.println(first + " " + last);
            if(first != last)
            {
               System.out.println("not a palindrome");
               check = false;
               break;
            }
            else
               check = true;
         }

This is specifically happening to the char variable last . When the String word = "Never odd or even". At j = 12, last = ' ' and the loop checks it with the condition (last<'a' || last>'z') then iterating last = word.charAt(j--); once again with j = 11. For some reason in the debugging tool, last still equals ' ', causing it iterate again with j = 10 & last = 'r'. The same problem occurs when String word = "Borrow or rob", but does not occur when equals to "a ppa" and "Borro b".

This causes certain palindromes to be classified as not.

The //last = word.charAt(j); was to assign the value again and that fixed the problem, but I just want to understand why this happens in the first place. Thanks for reading.

It is happening because of post-increment/decrement. Change it to pre-increment/decrement ie

Replace

first = word.charAt(i++);
last = word.charAt(j--);

with

first = word.charAt(++i);
last = word.charAt(--j);

Note that in the case of post-increment/decrement, first, the assignment happens and then the change (increment/decrement) happens eg last = word.charAt(j--) is processed as follows:

last = word.charAt(j);
j = j -1;

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