-----

CS 5: Common bugs

-----

Common hard-to-find code bugs

(1) You used the value of an expression like i++, e.g.

   while (i < 25){
      ...
      i = i++;
      ...};

i++ by itself resets the value of i and "i = i++" doesn't do what you think. Rewrite as

   while (i < 25){
      ...
      i++;
      ...};
(2) You used = to test for equality, as in:
    i = HMCSupport.in.nextInt();
    while (i = 3){
      i = HMCSupport.in.nextInt();
      }

The statement "i=3" resets the value of i to 3 rather than testing whether i equals 3. The java compiler will detect this bug, but you may find it hard to see where your error was. Rewrite using ==.

(3) You used == to compare the contents of two strings.

   String str1, str2;
   if (str1 == str2) { 
      ...
      }

This will make it past the compiler but does not do what you intended. Use the equals method to compare the contents of two strings, e.g.

   String str1, str2;
   if (str1.equals(str2)) { 
      ...
      }

This page is maintained by Margaret Fleck.