Question

I'm taking an AP Computer Science course and have a brief question about the purpose of a particular variable in Java program. Below is my own slight adaption of a certain program in my textbook...

public class Nineteen {
        public static void main(String[] args) {
                int valid = checkNumber(6145);
        }

        public static int checkNumber(int n)
        {
                int d1,d2,d3,checkDigit,nRemaining,rem;
                checkDigit = n % 10;
                nRemaining = n / 10;
                d3 = nRemaining % 10;
                nRemaining /= 10;
                d2 = nRemaining % 10;
                nRemaining /= 10;
                d1 = nRemaining % 10;
                rem = (d1 + d2 + d3) % 7;
                System.out.println("checkNumber executed.");
                if (rem == checkDigit) {
                        System.out.println("Equal");
                }
                return 1;
        }
}

My book says the purpose of nRemaining in this program above is to enhance the readability of the program, not to be used as a left-hand operand for integer division. Can anyone help explain why this is? I'm certain the program can be rewritten in a more condensed way, but is that the most obvious purpose of it?

Était-ce utile?

La solution

In essence, the purpose of additional variables in a context like this is to break down the computation process into smaller more human understandable steps. You could combine these operations into much more dense instruction sets, however then it would be more difficult to understand and, critically, to debug. To that end, a quote...

"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." --Brian Kernighan

(just in case: https://stackoverflow.com/questions/1103299/help-me-understand-this-brian-kernighan-quote)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top