我编写了这段代码,但每次尝试通过System.out.print
语句向用户显示输出时都会出错。
代码的目的是检查数组是否是"回文"。
import java.util.Scanner;
public class u {
public static void main(String[] args) {
int [] arr = {1,2,3,4,3,2,1};
int counter1 = 0,counter2 = arr.length-1;
int x = arr.length/2;
while (counter1 < x ) {
if (arr[counter1] == arr [counter2]){
counter1++;
counter2--;
} else {System.out.println(":("); break;}
}
System.out.println("Bingo!");
}}
答案 0 :(得分:1)
如果问题是程序总是打印&#34; Bingo!&#34;它是因为break
只结束了while循环。 &#34; Bingo!&#34; line在while循环之外,所以它仍然会被调用。您可以通过将break
更改为return
来避免这种情况。您也可以使用标签:
x: {
while(...) {
...
else break x;
}
System.out.println("Bingo!");
}
答案 1 :(得分:0)
import java.util.Scanner;
public class u {
public static void main(String[] args) {
boolean d = false;
int [] arr = {2,9,3,4,4,3,9,2};
int counter1 = 0,counter2 = arr.length-1;
int x = arr.length/2;
while (counter1 < x ) {
d = false;
if (arr[counter1] == arr [counter2]){
counter1++;
counter2--;
d = true;
} else break;
}
if (d)
System.out.println("Bingo!");
else System.out.println(":(");
}}