Pregunta

supongo que estoy recibiendo este error ya que la cadena está tratando de subcadena un valor null. Pero no sería la parte ".length() > 0" eliminar ese problema?

Aquí está el fragmento de código Java:

if (itemdescription.length() > 0) {
    pstmt2.setString(3, itemdescription.substring(0,38));
} 
else { 
    pstmt2.setString(3, "_");
} 

Tengo este error:

 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)
¿Fue útil?

Solución

  

I "M adivinar que estoy recibiendo este error   porque la cadena está tratando de   subcadena un valor nulo. Pero no lo haría   la" .length)> 0" (eliminar parte   esa cuestión?

No, llamando itemdescription.length () cuando ITEMDESCRIPTION es nulo no generaría una StringIndexOutOfBoundsException, sino más bien una NullPointerException ya que en esencia se trata de llamar a un método en nula .

Como otros han indicado, StringIndexOutOfBoundsException indica que no es ITEMDESCRIPTION al menos 38 caracteres de longitud. Es posible que desee manejar tanto las condiciones (I suponiendo que desea truncar):

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

Puede ser un buen lugar para una función de utilidad si lo hace mucho ...

Otros consejos

Es una lástima que substring no se implementa de manera que se encarga de cadenas cortas - como en otros idiomas, por ejemplo, Python.

Ok, no podemos cambiar eso y tener en cuenta este caso el borde cada vez que utilizamos substr, en lugar de if-else cláusulas Me gustaría ir para esta variante más corta:

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

Usted realmente necesita para comprobar si la longitud de la cadena es mayor que o igual a 38.

Yo recomendaría Apache Commons Lang . Una sola línea se ocupa del problema.

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

substring(0,38) significa que la cadena tiene que ser de 38 caracteres o más. Si no es así, el "índice de cuerdas está fuera de alcance".

if (itemdescription != null && itemdescription.length() > 0) {
    pstmt2.setString(3, itemdescription.substring(0, Math.min(itemdescription.length(), 38))); 
} else { 
    pstmt2.setString(3, "_"); 
}

Estoy asumiendo que su columna es de 38 caracteres de longitud, por lo que desea truncado itemdescription para encajar dentro de la base de datos. Una función de utilidad como el siguiente debe hacer lo que quiera:

/**
 * Truncates s to fit within len. If s is null, null is returned.
 **/
public String truncate(String s, int len) { 
  if (s == null) return null;
  return s.substring(0, Math.min(len, s.length()));
}

a continuación, sólo lo llama así:

String value = "_";
if (itemdescription != null && itemdescription.length() > 0) {
  value = truncate(itemdescription, 38);
}

pstmt2.setString(3, value);

substring método de Java falla al intentar y obtener una subcadena a partir de un índice que es más larga que la cadena.

Una alternativa fácil es utilizar Apache Commons StringUtils.substring :

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

Tenga en cuenta, si no se puede utilizar Apache Commons lib por alguna razón, sólo podría agarrar las piezas que necesita de la fuente

// Substring
//-----------------------------------------------------------------------
/**
 * <p>Gets a substring from the specified String avoiding exceptions.</p>
 *
 * <p>A negative start position can be used to start {@code n}
 * characters from the end of the String.</p>
 *
 * <p>A {@code null} String will return {@code null}.
 * An empty ("") String will return "".</p>
 *
 * <pre>
 * 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"
 * </pre>
 *
 * @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, {@code null} 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);
}

itemdescription es más corto que 38 caracteres. Por lo que el StringOutOfBoundsException está siendo lanzada.

Comprobación .length() > 0 simplemente hace que el String tiene algún valor no nulo, lo que hay que hacer es comprobar que la longitud es lo suficientemente largo. Usted podría intentar:

if(itemdescription.length() > 38)
  ...

Debe comprobar la longitud de cadena. Usted asume que se puede hacer substring(0,38), siempre y cuando la cadena no es null, pero que realmente necesita la cadena a tener una longitud de al menos 38 caracteres.

Cuando este es el caso, yo uso partidos en lugar de subcadena .

subcadena

if( myString.substring(1,17).equals("Someting I expect") ) {
    // Do stuff
}
// Does NOT work if myString is too short

partidos (debe utilizar la notación de expresiones regulares):

if( myString.matches("Someting I expect.*") ) {
    // Do stuff
}
// This works with all strings

Usted consigue esto si ITEMDESCRIPTION es más corto que 38 caracteres

Usted puede mirar el cual se lanzan excepciones y cuando en la API de JAVA en el que caso de Cadena # substring (int, int): https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#substring-int-int-

substring
public String substring(int beginIndex, int endIndex)
   . . .

Throws:
 IndexOutOfBoundsException
 if the beginIndex is negative,
 or endIndex is larger than the length of this String object, 
 or beginIndex is larger than endIndex.



(same applies to previous java versions as well)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top