0

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.

3
  • Please provide an example that causes this behavior Commented May 30, 2012 at 14:26
  • I don't think this is line 98 char [] Passwd = Pass.toCharArray(); Commented May 30, 2012 at 14:29
  • i believe the compiler may have pinpointed the wrong line, as it sometimes does. Commented May 30, 2012 at 14:45

5 Answers 5

3

indexOf() returns -1 when the argument can't be found. I bet that the string you are searching does not have one of the characters you are searching for and it is causing an invalid index when you try to get a substring.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! It shouldn't be... it's finding a plaintext username and password in a file containing only "username:password.", so I presume I've screwed up one of the searches...
3

try to use contains() before indexOf() for yor string to avoid the situations when indexOf() returns -1 and you try to get substring with the -1 position.

2 Comments

How exactly should I use contains()?
e.g.: if(myString.contains(someChar) && myString.contains(someOhterChar)) { String subString = myString.substring(myString.indexOf(someChar), myString.indexOf(someOhterChar))
2

String().indexOf will return -1 if there is no match

String().substring will throw an StringIndexOutOfBoundsException if you give it a negative begin value.

This is all documented at http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html

Thus, I'd look at this line of code:

String logdat = logindat.substring(startUsnm, logindat.indexOf("."));

This will fail if usnm is not in logindat

1 Comment

substring() Throws: IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
0

You should really look at those lines:

        int startUsnm = logindat.indexOf(usnm);
        int tendUsnm = logdat.indexOf(':');
        int endUsnm = startUsnm + tendUsnm;
        int startPass = endUsnm + 1;
        int tendPass = logdat.indexOf('.');
        int endPass = startPass + tendPass;
        String Usnm = logindat.substring(startUsnm, endUsnm);
        String Pass = logindat.substring(startPass, endPass);

Suppose you have file like this:


user:pass.


so:

  • startUsnm = 0 //first char
  • tendUsnm = 4 // index of : char
  • endUsnm = 4 // sum? this is probably not what you intent to do
  • startPass = 5 // p char
  • tendPass = 9 // . char
  • endPass = 14 // sum again? Those integers are indexes - will throw IndexOutOfBounds

And consider also that indexOf will return -1 value if there is no such match in given String.

1 Comment

the summed integers are for if the username required is not the first in the users.fra file; id est, it may contain "username:password.usrn:pass." and I only seek usrn, not username. This should give me the position of the end of the username with respect to the whole string. Which I've just realised is a pointless exercise, as I have a string which is only the index of usrn through to "."... Will now adjust.
0

A lot of things can be wrong. You'll have to check what is printed.

An exemple :

int startUsnm = logindat.indexOf(usnm);
String logdat = logindat.substring(startUsnm, logindat.indexOf("."));

If you don't have "Username: " in logindat, it produces the exception you see.

EDIT : Note that if you want to allow "username:" (and not only "Username:"), you can do this :

 int startUsnm = logindat.toLowerCase().indexOf("username:");

And test that startUsnm is >= 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.