String index exception java

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; > 
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.(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!

Читайте также:  Html form input type text css

Источник

Java substring: ‘String index out of range’

I guess I’m getting this error because the string is trying to substring a null value. But wouldn’t the «.length() > 0» part eliminate that issue? Here is the Java snippet:

if (itemdescription.length() > 0) < pstmt2.setString(3, itemdescription.substring(0,38)); >else
 java.lang.StringIndexOutOfBoundsException: String index out of range: 38 at java.lang.String.substring(Unknown Source) at MASInsert2.itemimport(MASInsert2.java:192) at MASInsert2.processRequest(MASInsert2.java:125) at MASInsert2.doGet(MASInsert2.java:219) at javax.servlet.http.HttpServlet.service(HttpServlet.java:627) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174) at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:835) at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:640) at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1286) at java.lang.Thread.run(Unknown Source) 

13 Answers 13

It is a pity that substring is not implemented in a way that handles short strings – like in other languages e.g. Python.

Ok, we cannot change that and have to consider this edge case every time we use substr , instead of if-else clauses I would go for this shorter variant:

myText.substring(0, Math.min(6, myText.length())) 

I»m guessing i’m getting this error because the string is trying to substring a Null value. But wouldn’t the «.length() > 0» part eliminate that issue?

No, calling itemdescription.length() when itemdescription is null would not generate a StringIndexOutOfBoundsException, but rather a NullPointerException since you would essentially be trying to call a method on null.

As others have indicated, StringIndexOutOfBoundsException indicates that itemdescription is not at least 38 characters long. You probably want to handle both conditions (I assuming you want to truncate):

final String value; if (itemdescription == null || itemdescription.length() else if (itemdescription.length() else < value = itemdescription.substring(0, 38); >pstmt2.setString(3, value); 

Might be a good place for a utility function if you do that a lot.

I would recommend apache commons lang. A one-liner takes care of the problem.

pstmt2.setString(3, StringUtils.defaultIfEmpty( StringUtils.subString(itemdescription,0, 38), "_")); 

You really need to check if the string’s length is greater to or equal to 38.

Читайте также:  Parse html from php

Java’s substring method fails when you try and get a substring starting at an index which is longer than the string.

public static String substring(String str, int start) Gets a substring from the specified String avoiding exceptions. A negative start position can be used to start n characters from the end of the String. A null String will return null. An empty ("") String will return "". StringUtils.substring(null, *) = null StringUtils.substring("", *) = "" StringUtils.substring("abc", 0) = "abc" StringUtils.substring("abc", 2) = "c" StringUtils.substring("abc", 4) = "" StringUtils.substring("abc", -2) = "bc" StringUtils.substring("abc", -4) = "abc" Parameters: str - the String to get the substring from, may be null start - the position to start from, negative means count back from the end of the String by this many characters Returns: substring from start position, null if null String input 

Note, if you can’t use Apache Commons lib for some reason, you could just grab the parts you need from the source

// Substring //----------------------------------------------------------------------- /** * 

Gets a substring from the specified String avoiding exceptions.

* *

A negative start position can be used to start * characters from the end of the String.

* *

A String will return . * An empty ("") String will return "".

* *
* StringUtils.substring(null, *) = null * StringUtils.substring("", *) = "" * StringUtils.substring("abc", 0) = "abc" * StringUtils.substring("abc", 2) = "c" * StringUtils.substring("abc", 4) = "" * StringUtils.substring("abc", -2) = "bc" * StringUtils.substring("abc", -4) = "abc" *

* * @param str the String to get the substring from, may be null * @param start the position to start from, negative means * count back from the end of the String by this many characters * @return substring from start position, if null String input */ public static String substring(final String str, int start) < if (str == null) < return null; >// handle negatives, which means last n characters if (start < 0) < start = str.length() + start; // remember start is negative >if (start < 0) < start = 0; >if (start > str.length()) < return EMPTY; >return str.substring(start); >

Источник

Java — «String index out of range» exception

I wrote this little function just for practice, but an exception («String index out of range: 29») is thrown and I don’t know why. (I know this isn’t the best way to write this function and can I use regular expressions.) This is the code:

public String retString(String x) < int j=0; int i=0; StringBuffer y = new StringBuffer(x); try < while ( y.charAt(i) != '\0' ) < if (y.charAt(i) != ' ') < y.setCharAt(j, y.charAt(i)); i++; j++; >else < y.setCharAt(j, y.charAt(i)); i++; j++; while (y.charAt(i) == ' ') i++; >> y.setCharAt(j,'\0'); > finally < System.out.println("lalalalololo " ); >return y.toString(); > 

5 Answers 5

Are you translating this code from another language? You are looping through the string until you reach a null character ( «\0» ), but Java doesn’t conventionally use these in strings. In C, this would work, but in your case you should try

at the end of your code will not resize the string, if that is what you are expecting. You should instead try

This exception is an IndexOutOfBoundsException but more particularly, a StringIndexOutOfBoundsException (which is derived from IndexOutOfBoundsException). The reason for receiving an error such as this is because you are exceeding the bounds of an indexable collection. This is something C/C++ does not do (you check bounds of collections manually) whereas Java has these built into their collections to avoid issues such as this. In this case, you’re using the String object like an array (probably what it is in implementation) and going over the boundary of the String.

Java does not expose the null terminator in the public interface of String. In other words, you cannot determine the end of the String by searching for the null terminator. Rather, the ideal way to do this is by ensuring you do not exceed the length of the string.

Источник

Оцените статью