Hello
I am a very beginner in java programming and I am trying to learn on my one using the "objects first with java" book. So I would like to know if there are differences between my solution and the one the book gives. Actually the result is the same so mine is also correct but I wonder if one way is actually better to use than the other and if yes the reasons why.
First:
private ArrayList<String> files; /** takes a single integer and checks whether it is a valid index for the current * state of the collection. If the parameter is not valid, print an error message, otherwise print nothing. */ public void checkIndex(int indexNumber) { if(indexNumber < 0 || indexNumber > files.size() - 1) { System.out.println("Error: index number not valid!"); } } public void checkIndex(int checkIndex) { int isValid = checkIndex; if (!((0 < isValid) && (isValid < (files.size()-1)))) { System.out.println("Error: index number not valid!"); } }
note. I post only the field and the method of my class...
The first checkIndex method is mine and the second is the solution given. I want to ask first why to use a local variable when you can directly use the parameter for the test of the if statement, and secondly I know that a||b is equal to !(!a && !b) but I am baffled about the use of the latter by the book because it mentions all the time about trying to make our code as less complicated as possible and at the same time is using a more complicate expression.
Are there reasons why the second method is better? I want to know so that in that case to adapt my way of thinking in order to write more accurate code...
p.s. I have nobody to assist me and help me out with programming neither to give me a deeper explanation to the concepts I am going through the book and sometimes I am really struggling and feel frustrated so please excuse me for my ignorance...
Thank you in advance