新代码:
我不知道这里发生了什么,我收到了这个错误:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1949)
at client0_0_2.loginToClient(client0_0_2.java:98)
at client0_0_2.general(client0_0_2.java:196)
at client0_0_2.<init>(client0_0_2.java:208)
at client0_0_2.main(client0_0_2.java:215)
这是导致错误的方法的内容:
public String loginToClient() throws FileNotFoundException, IOException {
//decryptUsers();
int tries;
tries = 5;
while (tries > 0) {
System.out.println("LOGIN");
String usnm = c.readLine("Username: ");
char [] passwd = c.readPassword("Password: ");
users = new FileInputStream("users.fra");
DataInputStream dis = new DataInputStream(users);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String logindat = br.readLine();
System.out.println(logindat);
int startUsnm = logindat.indexOf(usnm);
String logdat = logindat.substring(startUsnm, logindat.indexOf("."));
if (startUsnm == -1) {
System.err.println("Username not recognised, please try another or create user.");
usnm = "INV";
return usnm;
}
else {
int tendUsnm = logdat.indexOf(':');
int startPass = endUsnm + 1;
int tendPass = logdat.indexOf('.');
String Usnm = logdat.substring("0", tendUsnm);
String Pass = logdat.substring(startPass, endPass);
char [] Passwd = Pass.toCharArray();
if (usnm.equals(Usnm)) {
if (Arrays.equals(passwd,Passwd)) {
System.out.println ("Logged in. Welcome, " + usnm + ".");
String data = "LOGIN: " + usnm;
printLog(data);
//encryptUsers();
return usnm;
}
else {
System.out.println ("Incorrect password, please try again.");
String data = "PASWFAIL: " + usnm;
printLog(data);
tries -= 1;
}
}
else {
System.out.println ("Username not recognised.");
printLog("USNAMFAIL");
usnm = "INV";
return usnm;
//encrytUsers();
}
}
}
//encryptUsers();
System.exit(2);
return usnm;
}
它看起来有点像它试图访问某些东西的最后一个字符,这让它感到不安,但我不知道为什么。对新手有什么帮助吗?
编辑:
users.fra
包含username:password
在执行时。
注意:第 98 行是
char [] Passwd = Pass.toCharArray();
nb 不是功课,个人项目。
将添加一个方法来处理用户名不在的事件users.fra
。