我正在为学校做一个项目,但对我目前所处的位置感到困惑。当我运行我的项目时,VM 似乎陷入了循环并且不会加载(应弹出一个控制台,允许我为 CombinationLock 类 setDigit()
方法输入字符)。我相信这与我的 Interface.java
类中的 for 循环有关。如果有人可以看看并引导我朝着正确的方向前进,那将不胜感激。非常感谢!
接口(interface).java
import java.util.*;
public class Interface
{
public static void main() {
Scanner in = new Scanner(System.in);
CombinationLock combo = new CombinationLock();
for(int i = 0; i < 3; i++) {
String ltr = in.nextLine();
combo.setDigit(ltr.charAt(0), i);
System.out.println("Digit " + i + " has been set to " + ltr);
}
}
}
CombinationLock.java
public class CombinationLock
{
String[] combo = new String[3];
public CombinationLock() { }
public boolean setDigit(char letter, int index) {
if (Character.isDigit(letter)) {
return false;
}
combo[index] = String.valueOf(letter);
return true;
}
public boolean unlock(String combo) {
if (combo.length() > 3) {
return false; //Longer then it can be, not valid
}
char[] comboArray = combo.toCharArray();
for (char c : comboArray) {
if (Character.isDigit(c)) {
return false; //Contains numbers, not valid
}
}
boolean valid = true;
for (int i = 0; i < 3; i++) {
if (combo.charAt(i) != comboArray[i] && valid == true) {
valid = false;
break;
}
}
return valid;
}
}
最佳答案
您已经在 CombinationLock
类中初始化了长度为 0
的 combo
数组作为 String[] combo = {};
。当您调用 combo.setDigit(ltr.charAt(0), i);
时,这是导致 ArrayIndexOutOfBoundsException
的原因。请更正初始化。我相信你想捕获 3 个输入,在这种情况下,请在 CombinationLock
中初始化 combo
,长度为 3,如下所示:
String[] combo = new String[3];
关于java - BlueJ中的for循环输入(无限循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13115028/