-2

I want to display palindromes for the product of two, 3 digit numbers, ranging from 100-999. Something is wrong with my code, I can't quite place it.

public static void main (String[] args) {
   int num = 0, remainder = 0, sum = 0, b;
   int temp;

   for (b = 999; b >= 100; b--) {
      for (a = 999; a >= 100; a--) {
         num = (a * b);
         temp = num;

         while (num > 0) { 
            remainder = num % 10;  
            sum = (sum * 10) + remainder;    
            num = num / 10;
         }

         if (temp == sum)   
            System.out.println(temp);           
      }
   }
}

I expect an output, but I do not get any.

Dave Cousineau
  • 12,154
  • 8
  • 64
  • 80
ArbitraryChoices
  • 243
  • 1
  • 11

2 Answers2

3

That code never resets sum to zero. Declaring variables at the point of first use helps avoid this kind of problem.

public static void main(String[] args) {
  for (int b = 999; b >= 100; b--) {
    for (int a = 999; a >= 100; a--) {
      int sum = 0;
      int num = (a * b);
      int temp = num;

      while (num > 0) {
        int remainder = num % 10;
        sum = (sum * 10) + remainder;
        num = num / 10;
      }

      if (temp == sum) {
        System.out.println(temp);
      }
    }
  }
}
dnault
  • 8,340
  • 1
  • 34
  • 53
2

I copied your file, and right before your if-statement, I put this line in my copy:

System.out.println(temp + " " + sum);

So, after running the code, here were the results.

(it counts up each time the print statement is ran)

Format: temp, sum

1. temp = 98488, sum = -714680119

2. temp = 98384, sum = 243953829

3. temp = 98280, sum = -31332991

>4000. temp = 10000, sum = -110845663

Your temp is never equal to your sum, which means that your if statement will never run your print command. Here is a link to a pastebin which will contain all of the results. It is so long that I am not allowed to place it here (if I could nobody would want to read it) https://pastebin.com/7WxYKdgy

This is likely because of integer overflow. Learn more. How does Java handle integer underflows and overflows and how would you check for it?

FailingCoder
  • 757
  • 1
  • 8
  • 20