Java Reference
In-Depth Information
15.
public static boolean isVowel(char c) {
c = Character.toLowerCase(c); // case-insensitive
return c == 'a' || c == 'e' || c == 'i' ||
c == 'o' || c == 'u';
}
An alternative version follows:
public static boolean isVowel(char c) {
String vowels = "aeiouAEIOU";
return vowels.indexOf(c) >= 0;
}
16.
In this code the
boolean
flag isn't being used properly, because if the code finds a
factor of the number,
prime
will be set to
false
, but on the next pass through the
loop, if the next number isn't a factor,
prime
will be reset to
true
again. The fol-
lowing code fixes the problem:
public static boolean isPrime(int n) {
boolean prime = true;
for (int i = 2; i < n; i++) {
if (n % i == 0) {
prime = false;
}
}
return prime;
}
17.
In this code the
boolean
flag isn't being used properly, because if the code finds
the character,
found
will be set to
true
, but on the next pass through the loop, if
the next character isn't
ch
,
found
will be reset to
false
again. The following code
fixes the problem:
public static boolean contains(String str, char ch) {
boolean found = false;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ch) {
found = true;
}
}
return found;
}
18.
public static boolean startEndSame(String str) {
return str.charAt(0) == str.charAt(str.length() - 1);
}
Search WWH ::
Custom Search