AP计算机教程5-4:常见错误
- 忘记在
while
循环中变更循环条件所涉及的变量,造成无限循环。public class Test { public static void main(String[] args) { int x = 3; while (x > 0) { System.out.println(x); } } }
- 弄错
for
循环的开始和结束条件,这往往会导致读取某个数组或字符串长度以外的元素或字符,造成out of bounds error
。public class Test { public static void main(String[] args) { String result = ""; String message = "watch out"; int pos = 0; while (pos < message.length()) { result = result + message.substring(pos,pos+2); pos = pos + 1; } System.out.println(result); } }
- 在循环中(不正确的)使用
return
语句,造成循环提前结束。public class Test { public static boolean isInOrder(String check) { int pos = 0; while (pos < check.length() - 1) { if (check.substring(pos, pos+1).compareTo(check.substring(pos+1, pos+2)) < 0) return true; pos++; } return false; } public static void main(String[] args) { System.out.println(isInOrder("abca")); System.out.println(isInOrder("abc")); } }
0 条评论