Domanda

sto cercando di indovinare che sto ricevendo questo errore perché la stringa sta cercando di sottostringa un valore null. Ma non sarebbe la parte ".length() > 0" eliminare quel problema?

Ecco il frammento Java:

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

ho ottenuto questo errore:

 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)
È stato utile?

Soluzione

  

I "m indovinando sto ottenendo questo errore   perché la stringa sta cercando di   substring un valore Null. Ma no   il" .length)> 0" (parte eliminare   tale questione?

No, chiamando itemdescription.length () quando itemdescription è null non genererebbe uno StringIndexOutOfBoundsException, ma piuttosto un NullPointerException dal momento che si sarebbe essenzialmente cercando di chiamare un metodo su nullo .

Come altri hanno indicato, StringIndexOutOfBoundsException indica che itemdescription non è lunga almeno 38 caratteri. Probabilmente si desidera gestire entrambe le condizioni (I supponendo che si desidera troncare):

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

Potrebbe essere un buon posto per una funzione di utilità se si fa che un sacco ...

Altri suggerimenti

E 'un peccato che substring non è implementata in modo che gestisce le stringhe brevi - come ad esempio in altre lingue Python.

Ok, non possiamo cambiare la situazione e prendere in considerazione questo caso limite ogni volta che usiamo substr, invece di if-else clausole vorrei andare per questa variante più corta:

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

Hai davvero bisogno di controllare se la lunghezza della stringa è maggiore o uguale a 38.

Apache Commons Lang . Un one-liner prende cura del problema.

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

substring(0,38) significa che la stringa deve essere 38 caratteri o più. In caso contrario, l ' "indice String è fuori portata".

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

sto assumendo la vostra colonna è di 38 caratteri di lunghezza, in modo che si desidera troncare itemdescription per adattarsi all'interno del database. Una funzione di utilità come la seguente dovrebbe fare quello che vuoi:

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

poi basta chiamare in questo modo:

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

pstmt2.setString(3, value);

metodo substring Java non riesce quando si tenta e ottenere una sottostringa a partire da un indice che è più lungo della stringa.

Un facile alternativa è quella di utilizzare 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

Si noti, se non è possibile utilizzare Apache Commons lib per qualche motivo, si può solo afferrare i pezzi necessari dalla sorgente

// 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 è più breve di 38 caratteri. È per questo che il StringOutOfBoundsException viene gettata.

Controllo .length() > 0 fa semplicemente che il String ha un certo valore non nullo, ciò che devi fare è controllare che la lunghezza è abbastanza lungo. Si potrebbe provare:

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

È necessario controllare la lunghezza della stringa. L'utente si assume che si può fare substring(0,38) finché String non è null, ma hai veramente bisogno la stringa per essere di lunghezza di almeno 38 caratteri.

Quando questo è opportuno, io uso corrisponde al posto di stringa .

stringa :

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

corrisponde (deve utilizzare Regex notazione):

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

È possibile ottenere questo se itemdescription è più breve di 38 caratteri

Si può guardare che vengono generate eccezioni e quando in Java API in voi caso per String # sottostringa (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)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top