Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: 'string index out of range: -1' exception using indexOf()

Weird problem. I run this (very elementary) procedure to find a username and password in a file, and the program should compare the password entered to the password saved. Every time, however, i get a strange String index out of range: -1 exception. I've suffered a similar problem before, however this time the indexOf('.') call is returning -1; which it doesn't like. Why is indexOf() returning -1 if it causes an error? Here's the source:

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);
            if (logindat.contains(usnm) == null) {
                System.err.println("Username not recognised, please try another or create user.");
                usnm = "INV";
                return usnm;
            }
            else {
                int startUsnm = logindat.indexOf(usnm);
                System.out.println("startUsnm: " + startUsnm);
                String logdat = logindat.substring(startUsnm, logindat.indexOf("."));
                System.out.println("logdat: " + logdat);
                int endUsnm = logdat.indexOf(':'); 
                System.out.println("endUsnm: " + endUsnm);
                int usnmend = endUsnm - 1;
                System.out.println("usnmend: " + usnmend);
                int startPass = endUsnm + 1;
                System.out.println("startPass: " + startPass);
                int endPass = logdat.indexOf('.');
                System.out.println("endPass: " + endPass);
                String Usnm = logdat.substring(0, usnmend);
                System.out.println("Usnm: " + Usnm);
                int passend = endPass - 1;
                System.out.println("passend: " + passend);
                String Pass = logdat.substring(startPass, passend);
                System.out.println("Pass: " + Pass);
                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;
    }

And here's some input/output:

Startup initiated.
Logfile exists.
Users file exists.
New user? n
ELSE
LOGIN
Username: rik
Password: 
rik:55.
startUsnm: 0
endUsnm: 3
startPass: 4
endPass: -1
Usnm: rik
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -5
    at java.lang.String.substring(String.java:1949)
    at client0_0_2.loginToClient(client0_0_2.java:103)
    at client0_0_2.general(client0_0_2.java:209)
    at client0_0_2.<init>(client0_0_2.java:221)
    at client0_0_2.main(client0_0_2.java:228)

EDIT : SOLUTION FOUND!

For some reason, indexOf() does not want to find a '.'- when replaced with a hyphen('-'), however, it runs perfectly, seemingly!

like image 619
gossfunkel Avatar asked Jan 20 '26 12:01

gossfunkel


2 Answers

I think the error is in this line:

String Pass = logdat.substring(startPass, passend);

For some reason (you'll have to determine why), you compute passend by searching for . in the string. If . isn't present, indexOf returns -1 as a sentinel. This isn't the line that causes the exception, though. I think it's the above line, since if you try to compute a substring ending at passend when passend is -1, you would get the above error.

Try determining why your string doesn't contain a . in it.

Hope this helps!

like image 185
templatetypedef Avatar answered Jan 22 '26 02:01

templatetypedef


When indexOf() returns -1, it means that the value couldn't be found in the String. So, in this case, you're searching a String for '.' which doesn't exist in the String.

I would recommend that you always check the values of indexOf() after the call, and handle the -1 properly. For many cases, its probably sufficient to set it to either 0 or string.length(), depending on how you will use it later in your code.

Regardless, if you're expecting a '.' to exist and there isn't one, you'll need to debug through your code to find out what the value is, and where the '.' is missing.

like image 26
wattostudios Avatar answered Jan 22 '26 01:01

wattostudios



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!