【发布时间】:2018-05-05 08:14:21
【问题描述】:
所以,假设我有这个代码
String some = ("my name|username|password");
String[] split = some.split("|");
我想要这样的字符串
split[0] = "my name";
split[1] = "username";
split[0] = "password";
这是我的代码
String record = null;
FileReader in = null;
MainMenu menu = null;
public void checkLogin() throws FileNotFoundException, IOException, ArrayIndexOutOfBoundsException {
in = new FileReader("D:\\Login.txt");
BufferedReader br = new BufferedReader(in);
String username = txfUsername.getText();
String password = new String(txfPassword.getPassword());
while ((record = br.readLine()) != null) {
String[] split = record.split("-");
if (username.equals(split[1]) && password.equals(split[2])) {
JFrame frame = new JFrame();
menu = new MainMenu(split[0]);
this.setVisible(false);
menu.setVisible(true);
break;
}
}
if (menu == null) {
JOptionPane.showMessageDialog(null, "Username or Password wrong.");
}
}
这里是 login.txt
my name-user-pass
当我运行程序时,它会抛出 arrayindexoutofbound 异常 如何摆脱它?
【问题讨论】:
-
您需要向我们展示异常的完整堆栈跟踪,并告诉我们数组访问发生在程序中的哪些行号。您还需要打印出记录的值,以确保您正确读取它。
-
在调试器中查看
split的值 -
“当我运行程序时,它会抛出
ArrayIndexOutOfBoundsException异常。如何摆脱它?” 在执行split[1]和@987654330 之前检查split.length@,以确保您有 3 个值。如果您认为应该得到 3 个值,但没有得到 3 个值,则您调试代码以找出未满足您的期望的原因。