non può convertire da una stringa in numero intero
-
21-12-2019 - |
Domanda
Ho implementato un servizio che funziona bene.Il servizio ha la seguente proprietà:
@Property(name = MyService.PROXY_PORT, label = "Proxy Port", description = "Proxy Port", value= "8080")
private static final String PROXY_PORT = "proxy.port";
.
ottengo il valore della proprietà port
come segue:
..
...
properties = context.getProperties();
String port = properties.get(PROXY_PORT).toString();
...
.
port
in questo caso Risultati 8080
.Ora vorrei convertire questa stringa in numero intero.Ho provato quanto segue:
int portInt = Integer.parseInt(port);
int portInt2 = Integer.getInteger(port);
.
Entrambi i risultati NULL: (
Cosa ho fatto worng?
Soluzione
Se la porta ha un valore e non è nullo, prova:
int portInt = Integer.valueOf(port.trim());
. Altri suggerimenti
Considera l'utilizzo di Propestitutil , una classe di utilità creata esattamente per questo caso:
int port = PropertiesUtil.toInteger(properties.get(PROXY_PORT), 8080);
.
Il secondo parametro è il valore predefinito.
Prova se funziona:
int portInt = Integer.parseInt(port+""); // check if the port value is coming or not before parse it.
int portInt2 = Integer.getInteger(port+"");
. Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow