New code:
I have no idea what's going on here, I'm getting this error:
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)
and this is the contents of the method that's causing the error:
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;
}
It looks kinda like it's trying to access the last character of something and that's upsetting it, but I have no idea why. Any help for a total newbie?
edits:
users.fra
contains username:password
at the time of execution.
note: line 98 is the
char [] Passwd = Pass.toCharArray();
n.b. not homework, a personal project.
Will add in a method to deal with the event that username is not in users.fra
.