Question

Je devine que je reçois cette erreur parce que la chaîne tente de sous-chaîne d'une valeur de null. Mais ne serait pas la partie ".length() > 0" éliminer cette question?

Voici l'extrait de code Java:

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

Je suis cette erreur:

 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)
Était-ce utile?

La solution

  

I "devine que je reçois cette erreur   parce que la chaîne tente de   la sous-chaîne d'une valeur nulle. Mais ne   la partie » .length ()> 0" éliminer   cette question?

Non, appelant itemdescription.length () lorsque itemdescription est nul ne produirait pas une StringIndexOutOfBoundsException, mais plutôt un NullPointerException puisque vous serait essentiellement d'essayer d'appeler une méthode sur null .

Comme d'autres l'ont indiqué, StringIndexOutOfBoundsException indique que itemdescription est pas au moins 38 caractères. Vous voulez probablement gérer les deux conditions (je suppose que vous voulez tronquer):

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);

Peut-être un bon endroit pour une fonction d'utilité si vous le faites beaucoup ...

Autres conseils

Il est dommage que substring ne soit pas mise en œuvre d'une manière qui gère les chaînes courtes - comme dans d'autres langues par exemple Python.

Ok, nous ne pouvons pas changer cela et je dois considérer ce cas limite chaque fois que nous utilisons substr, au lieu de if-else clauses je pencherais pour cette variante plus courte:

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

Vous avez vraiment besoin de vérifier si est supérieure ou égale à 38 la longueur de la chaîne.

Je recommande apache communes lang . Un one-liner prend soin du problème.

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

substring(0,38) signifie la chaîne doit être 38 caractères ou plus. Dans le cas contraire, l ' « indice de chaîne est hors de portée ».

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

Je présume que votre colonne est de 38 caractères de longueur, de sorte que vous voulez troncature itemdescription pour se loger dans la base de données. Une fonction d'utilité comme suit devrait faire ce que vous voulez:

/**
 * 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()));
}

vous appelez simplement comme ceci:

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

pstmt2.setString(3, value);

méthode de substring Java échoue lorsque vous essayez d'obtenir une sous-chaîne à partir d'un indice qui est plus long que la chaîne.

Une alternative simple est d'utiliser 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

Notez que si vous ne pouvez pas utiliser lib Apache Commons pour une raison quelconque, vous pouvez simplement saisir les pièces dont vous avez besoin de la source

// 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 est plus court que 38 caractères. Ce qui est la raison pour laquelle la StringOutOfBoundsException est levée.

Vérification .length() > 0 fait simplement que le String a une valeur non nulle, ce que vous devez faire est de vérifier que la longueur est assez longue. Vous pouvez essayer:

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

Vous devez vérifier la longueur de chaîne. Vous supposez que vous pouvez faire substring(0,38) tant que chaîne n'est pas null, mais vous avez besoin en fait la chaîne à longueur d'au moins 38 caractères.

Lorsque cela est approprié, j'utilise correspond à au lieu de sous-chaîne .

sous-chaîne :

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

correspond à (doit utiliser la notation Regex):

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

Vous obtenez ceci si itemdescription est plus court que 38 caractères

Vous pouvez regarder les exceptions sont jetés et quand dans l'API JAVA en vous cas pour cordes # 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)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top