This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Theresa Marlin wrote:
This works for 150, but for a number like 6, it will print 2, 2
I don't know what I'm doing wrong or how to fix it
You have a pretty complex maneuver here...
Basically, you are doing the division to find the "other" divisor (the number that when multiplied to the divisor will yield the orig number) and then checking this "other" divisor to see if it is a divisor. The problem with this is... if the "other" divisor is not a whole number (which for non-factors, it isn't), it will round down. This rounding of the "other" divisor, can cause it to be a valid divisor, when testing it.
Why so complex? Why not test the divisor directly? What's wrong with "number % divisor"?
You have a test for number > 0 inside a loop while (number > 1). I hardly think that test is necessary.
I have been teaching undergraduates today and I been telling them off for using the wrong hardware. Then I showed them a pencil and a large eraser, which I think is the equipment you ought to use now, too
Take a number, any number, well 6, take a divisor, any divisor, well 2, and work out what number % (number / divisor) will come to. Can you concoct a simpler test which will work?
Now work out what the test after the else if does. What would happen if you simplify that test? Does that second test do anything useful at all?
Lose the bit about if (number == 1) Move the System.out.println() call after the end of your loop.
Joined: Sep 23, 2009
Thank you for your comments. I fear you are very right about my need to use a pencil and eraser. I had been trying to use my interactions window to do all the tests separately, but it was getting a bit confusing. I have amended my code.