java question

John R. Ghidiu john at rmdashrf.org
Mon Sep 8 02:56:07 EDT 2003


On Sun, 7 Sep 2003, Asheville Joe wrote:

> I don't know java, but shouldn't it just be an else, not an else if?
> Joe
>
> Riga, Anthony wrote:
>
> >Anyone know java? I need to be able to find out if a number is even or
> >odd when a user inputs the number into a text box or in the bash
> >screen.I know to use the modulus % and did if(number1 % 2 == 0)
> >                           number is even;
> >                           System.out. println("number is even");
> >                        else if
> >                          odd;

Yes. All told, your code should look like:

if (number1 % 2 == 0) {
  System.out.println("number is even.");
} else {
  System.out.println("number is odd.");
}

You would use an 'else if' clause if there were another condition to test
for, eg:

if (someCondition) {
  // Respond to some condition
} else if (someOtherCondition) {
  // Respond to some other condition
} else {
  // Default behavior
}

With out getting into to much language theory, this code has some
implications (note that the last 'else' clause is not necessary). for
example, in this case, the code in exactly one of the 'else' clauses will
be run, even if more than one condition is true. You can modify this by
just chaining several 'if' statements together, instead of if/else
if/else. Also, if you are using a literal value, you might consider using
a switch/case block instead (less typing).

-- 
John R. Ghidiu
john at rmdashrf.org

"Just don't create a file called -rf. :-)"
  - Larry Wall in <11393 at jpl-devvax.JPL.NASA.GOV>




More information about the nflug mailing list