你好,
我是java新手,我对这段代码有疑问。我在想这是否是循环问题或其他问题..
public static void main(String[] args) {
try {
Scanner scn = new Scanner(System.in);
int z = 0;
String input;
int[] ABArray = new int[2];
while (z == 0) {
System.out.println("Input X to terminate.");
System.out.print("Input: ");
input = scn.nextLine().toLowerCase();
for (int i = 0; i < input.length(); i++) {
char AB = input.charAt(i);
ABArray[AB - 'a']++;
}
if (ABArray[0] == 0 || ABArray[1] == 0) {
System.out.println("Not Equal");
System.out.println("");
} else if (ABArray[0] == ABArray[1]) {
System.out.println("Equal");
System.out.println("");
} else if (ABArray[0] != ABArray[1]) {
System.out.println("Not Equal");
if (ABArray[0] > ABArray[1]) {
System.out.println("The number of A is greater than B.");
} else if (ABArray[0] < ABArray[1]) {
System.out.println("The number of B is greater than A.");
}
System.out.println("");
}
}
} catch (ArrayIndexOutOfBoundsException X) { } //Terminates the program
}
问题是这样的
输入/输出
Input:
ABABAB
Output:
Equal
Input:
AABBB
Output:
Not Equal
The number of B is greater than A.
Input:
AABB //It is equal.
Output:
Not Equal //It says not.
The number of B is greater than A.
如您所见,问题是当我第一次输入等于A和B时,它说等于,当我输入不等于A和B时,但在第三次输入等于A和B时,它说不等于。
问题已解决。 感谢您的帮助。
最佳答案
每次开始在 while
循环中工作时,都必须将 ABArray
中的所有值设置为零。现在,在第三次启动 while
循环(使用 AABB
输入)时,您仍然保留上次运行循环时留下的值 - 5
位于数组的 0 索引元素中,6
位于数组的 1 索引元素中,因此程序会给出错误的输出。
关于java - 循环中出现一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20933260/