Quote (carteblanche @ Nov 27 2014 05:22pm)
Couple of reasons. Why do you think he's using nextInt(10)? why does the Random class even come with it? just use (int)(nextDouble() * 10) wherever you need it, it's not that long. The answer is clarity. it's important to be able to understand what you're doing without needing to know every little details.
Lets say you have an app that has several hundred classes and i ask you to find me everywhere you check if a number is even. if you used a single method isEven everywhere, the answer is as simple as finding the references to it. I'm sure you're thinking "Why would I ever want to find the reference count?" Lets say we want to change the functionality. instead of checking if it's divisible by two, we want to check if it's divisible by three. How fun does that sound to change it over 300 classes? inside a method, you can quickly change it and rename it.
Another reason is type safety. java supports the modulus operator for doubles. 3.2 % 2 is not 0, therefore it's an odd number, right? Wrong, since "odd" only applies to integers. by creating a method that only accepts integers, you create a layer of safety.
The first reason was the major reason, but the others are valid reasons as well.
you are confusing static and non-static. the point of having member variables (variables outside of methods) is to maintain state. in OP's assignment, the number of even and odd only matter inside the main method. keep in mind that main is just a method. what do you think will happen if i use another class as my driver, then i call OddEven.main(..) twice? it will work great the first time, but your results will be wrong the second time because you're maintaining the state from the first time.
does that make sense?
To expand just a tiny bit more, as carteblanche did an amazing job, there is something in OOP known as the
http://en.wikipedia.org/wiki/Single_responsibility_principle. In a nutshell, the description is in the title: every method, variable, class, etc should serve one single purpose. In context of OP's assignment, the main method should not have to know how to generate a Random number, determine if it is even/odd, and count each odd and even. That is 3 responsibilities. Actually, it is 4. Because the purpose of the
main method is to provide an entry point into the application. It is a special method. That is it's single responsibility. It's job is to handle command-line arguments and forward them on to the rest of the application as needed. Everything else should be encapsulated within it's own method/class/variable which will serve it's own single purpose. Even though the
isEven method is 1 mathematically operation, it provides greater clarity to anyone else reading the code. Everyone can see
isEven and know that this is a method with a specific purpose, and can be reused whenever someone wants that functionality elsewhere. After all, that is the point of encapsulating methods: reducing redundant code.