在初学循环中我们经常遇到什么时候应该停止循环,什么时候循环应该使用break。
String str = "上海自来水来自上海";
for (int i = 0; i < str.length() / 2; i++) {
char c1 = str.charAt(i);
char c2 = str.charAt(str.length() - 1 - i);
if (c1 != c2) {
System.out.print("不是回文数");
}
}
System.out.println("是回文数");
在这个例子中我们不难看出代码会在发现第一个不匹配的字符后立即打印出“不是回文数”,但即使之后的所有字符都匹配,它仍然会在循环结束后打印出“是回文数”。这会导致输出可能同时包含“不是回文数”和“是回文数”,这显然是不正确的。我们下面我将展示一个十分巧妙的方法。
String str = "上海自来水来自上海";
for (int i = 0; i < str.length() / 2; i++) {
char c1 = str.charAt(i);
char c2 = str.charAt(str.length() - 1 - i);
if (c1 != c2) {
System.out.print("不");
}
}
System.out.println("是回文数");
在这段代码中我们很好的解决了结果不正确的问题,是不是很奇妙,但是我们在向别人展示时别人可能需要花一点时间来读懂这个逻辑。因此我们应该把我们的代码的逻辑更加清晰
String str = "上海自来水来自海上";
int num = 0;//加入num变量
for (int i = 0; i < str.length() / 2; i++) {
//每次循环取出字符串的前后两个字符判断
char c1 = str.charAt(i);
char c2 = str.charAt(str.length() - 1 - i);
if (c1 == c2) {
num++;//每次判断若为true则num加一;
}
}
if (num == str.length() / 2) {
System.out.println("是回文数");
}else{
System.out.println("不是回文数");
}
在上面的例子中我们加入num变量当作计数器,每次字符相匹配时num的值就加一,这样别人在阅读我们的代码时可以清楚的看明白了。显然这还是不够的每次判断都有循环一遍,那么就让我们加入break试试看。
String str = "上海自来水来自上海";
boolean isPalindrome = true; // 假设字符串是回文
for (int i = 0; i < str.length() / 2; i++) {
char c1 = str.charAt(i);
char c2 = str.charAt(str.length() - 1 - i);
if (c1 != c2) {
isPalindrome = false; // 发现不匹配,设置标志为false
break; // 可以选择退出循环,因为已经确定不是回文了
}
}
if (isPalindrome) {
System.out.println("是回文字符串");
} else {
System.out.println("不是回文字符串");
}
在这串代码中我们先假设字符串是回文的,再经过判断每次取出的字符是否匹配,一旦不匹配就结束循环。这样是不是判断的次数就减少了。