|
if (condition) {
statements
}
else {
statements
}
where condition represents an expression which evaluates to a
boolean value (i.e., true or false)
and statements are a single Java statement or sequence of statements
separated by semicolons. The if-statement is used for branching:
depending on some condition, one sequence of Java statements is
executed or another. The else part can be omitted.
As an example we present a Java applet that prints the number of characters and digits of the text entered in the input field.
void countCharacters(String s) {
char[] word = s.toCharArray();
countDigits = 0;
countNonDigits = 0;
for (int i=0; i<word.length; i++) {
if (Character.isDigit(word[i])) {
countDigits++;
}
else {
countNonDigits++;
}
}
}
void countCharacters(String s) {
countDigits = 0;
countLetters = 0;
countOtherCharacters = 0;
char[] word = s.toCharArray();
for (int i=0; i<word.length; i++) {
if (Character.isDigit(word[i])) {
countDigits++;
}
else if (Character.isLetter(word[i])){
countLetters++;
}
else {
countOtherCharacters++;
}
}
}
Then the applet looks as follows: