Come posso convertire un String
in un int
in Java?
My String contiene solo numeri e voglio restituire il numero che rappresenta.
Ad esempio, data la stringa "1234"
il risultato dovrebbe essere il numero 1234
.
String myString = "1234";
int foo = Integer.parseInt(myString);
Se osservi la Documentazione Java noterai che il "catch" è che questa funzione può lanciare un NumberFormatException
, che ovviamente devi gestire:
int foo;
try {
foo = Integer.parseInt(myString);
}
catch (NumberFormatException e)
{
foo = 0;
}
(Questo trattamento imposta un numero errato su 0
, ma se lo desideri puoi fare qualcos'altro.)
In alternativa, è possibile utilizzare un metodo Ints
dalla libreria Guava, che in combinazione con Optional
di Java 8, costituisce un modo potente e conciso per convertire una stringa in un int:
import com.google.common.primitives.Ints;
int foo = Optional.ofNullable(myString)
.map(Ints::tryParse)
.orElse(0)
Ad esempio, qui ci sono due modi:
Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);
C'è una leggera differenza tra questi metodi:
valueOf
restituisce un'istanza nuova o memorizzata nella cache di Java.lang.Integer
parseInt
restituisce il primitivo int
. Lo stesso vale per tutti i casi: Short.valueOf
/parseShort
, Long.valueOf
/parseLong
, ecc.
Bene, un punto molto importante da considerare è che il parser Integer genera NumberFormatException come indicato in Javadoc .
int foo;
String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exception
String StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exception
try {
foo = Integer.parseInt(StringThatCouldBeANumberOrNot);
} catch (NumberFormatException e) {
//Will Throw exception!
//do something! anything to handle the exception.
}
try {
foo = Integer.parseInt(StringThatCouldBeANumberOrNot2);
} catch (NumberFormatException e) {
//No problem this time, but still it is good practice to care about exceptions.
//Never trust user input :)
//Do something! Anything to handle the exception.
}
È importante gestire questa eccezione quando si tenta di ottenere valori interi da argomenti divisi o l'analisi dinamica di qualcosa.
Fallo manualmente:
public static int strToInt( String str ){
int i = 0;
int num = 0;
boolean isNeg = false;
//Check for negative sign; if it's there, set the isNeg flag
if (str.charAt(0) == '-') {
isNeg = true;
i = 1;
}
//Process each character of the string;
while( i < str.length()) {
num *= 10;
num += str.charAt(i++) - '0'; //Minus the ASCII code of '0' to get the value of the charAt(i++).
}
if (isNeg)
num = -num;
return num;
}
Attualmente sto facendo un incarico per il college, dove non posso usare certe espressioni, come quelle sopra, e guardando la tabella ASCII, sono riuscito a farlo. È un codice molto più complesso, ma potrebbe aiutare gli altri a essere limitati come me.
La prima cosa da fare è ricevere l'input, in questo caso, una stringa di cifre; Lo chiamo String number
, e in questo caso, lo esemplificerò usando il numero 12, quindi String number = "12";
Un altro limite era il fatto che non potevo usare cicli ripetitivi, quindi un ciclo for
(che sarebbe stato perfetto) non può essere usato neanche. Questo ci limita un po ', ma poi di nuovo, questo è l'obiettivo. Poiché avevo solo bisogno di due cifre (prendendo le ultime due cifre), un semplice charAt
lo ha risolto:
// Obtaining the integer values of the char 1 and 2 in ASCII
int semilastdigitASCII = number.charAt(number.length()-2);
int lastdigitASCII = number.charAt(number.length()-1);
Avendo i codici, dobbiamo solo cercare il tavolo e apportare le modifiche necessarie:
double semilastdigit = semilastdigitASCII - 48; //A quick look, and -48 is the key
double lastdigit = lastdigitASCII - 48;
Ora, perché raddoppiare? Bene, a causa di un passaggio davvero "strano". Attualmente abbiamo due doppi, 1 e 2, ma dobbiamo trasformarlo in 12, non ci sono operazioni matematiche che possiamo fare.
Stiamo dividendo il secondo (lastdigit) per 10 nel modo 2/10 = 0.2
(quindi perché doppio) in questo modo:
lastdigit = lastdigit/10;
Questo è semplicemente giocare con i numeri. Stavamo trasformando l'ultima cifra in un decimale. Ma ora, guarda cosa succede:
double jointdigits = semilastdigit + lastdigit; // 1.0 + 0.2 = 1.2
Senza entrare troppo in matematica, stiamo semplicemente isolando le unità di un numero. Vedete, dal momento che consideriamo solo 0-9, dividendo per un multiplo di 10 è come creare una "scatola" in cui archiviarla (ripensateci quando il vostro insegnante di prima elementare vi spiegò che unità erano e cento). Così:
int finalnumber = (int) (jointdigits*10); // Be sure to use parentheses "()"
E tu ci vai. Hai trasformato una stringa di cifre (in questo caso, due cifre) in un numero intero composto da queste due cifre, considerando le seguenti limitazioni:
Una soluzione alternativa è usare Apache Commons ' NumberUtils:
int num = NumberUtils.toInt("1234");
L'utilità Apache è piacevole perché se la stringa è un formato numerico non valido, viene sempre restituito 0. Quindi salvarti il blocco catch try.
Integer.decode
Puoi anche usare public static Integer decode(String nm) throws NumberFormatException
.
Funziona anche per la base 8 e 16:
// base 10
Integer.parseInt("12"); // 12 - int
Integer.valueOf("12"); // 12 - Integer
Integer.decode("12"); // 12 - Integer
// base 8
// 10 (0,1,...,7,10,11,12)
Integer.parseInt("12", 8); // 10 - int
Integer.valueOf("12", 8); // 10 - Integer
Integer.decode("012"); // 10 - Integer
// base 16
// 18 (0,1,...,F,10,11,12)
Integer.parseInt("12",16); // 18 - int
Integer.valueOf("12",16); // 18 - Integer
Integer.decode("#12"); // 18 - Integer
Integer.decode("0x12"); // 18 - Integer
Integer.decode("0X12"); // 18 - Integer
// base 2
Integer.parseInt("11",2); // 3 - int
Integer.valueOf("11",2); // 3 - Integer
Se vuoi ottenere int
invece di Integer
puoi usare:
Unboxing:
int val = Integer.decode("12");
intValue()
:
Integer.decode("12").intValue();
Ogni volta che c'è la minima possibilità che la stringa data non contenga un numero intero, devi gestire questo caso speciale. Purtroppo, i metodi standard Java Integer::parseInt
e Integer::valueOf
lanciano un NumberFormatException
per segnalare questo caso speciale. Pertanto, è necessario utilizzare le eccezioni per il controllo del flusso, che è generalmente considerato uno stile di codifica errato.
Secondo me, questo caso speciale dovrebbe essere gestito restituendo un Optional<Integer>
. Poiché Java non offre un tale metodo, utilizzo il seguente wrapper:
private Optional<Integer> tryParseInteger(String string) {
try {
return Optional.of(Integer.valueOf(string));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
Uso:
// prints 1234
System.out.println(tryParseInteger("1234").orElse(-1));
// prints -1
System.out.println(tryParseInteger("foobar").orElse(-1));
Mentre questo utilizza ancora eccezioni per il controllo del flusso internamente, il codice di utilizzo diventa molto pulito.
Convertire una stringa in un int è più complicato della semplice conversione di un numero. Hai pensato ai seguenti problemi:
Metodi per farlo:
1. Integer.parseInt(s)
2. Integer.parseInt(s, radix)
3. Integer.parseInt(s, beginIndex, endIndex, radix)
4. Integer.parseUnsignedInt(s)
5. Integer.parseUnsignedInt(s, radix)
6. Integer.parseUnsignedInt(s, beginIndex, endIndex, radix)
7. Integer.valueOf(s)
8. Integer.valueOf(s, radix)
9. Integer.decode(s)
10. NumberUtils.toInt(s)
11. NumberUtils.toInt(s, defaultValue)
Integer.valueOf produce oggetto intero, tutti gli altri metodi - int primitivo.
Gli ultimi 2 metodi da commons-lang3 e il grande articolo sulla conversione qui .
Possiamo usare il metodo parseInt(String str)
della classe wrapper Integer
per convertire un valore String in un valore intero.
Per esempio:
String strValue = "12345";
Integer intValue = Integer.parseInt(strVal);
La classe Integer
fornisce anche il metodo valueOf(String str)
:
String strValue = "12345";
Integer intValue = Integer.valueOf(strValue);
Possiamo anche usare toInt(String strValue)
di NumberUtils Utility Class per la conversione:
String strValue = "12345";
Integer intValue = NumberUtils.toInt(strValue);
Usa Integer.parseInt(yourString)
Ricorda le seguenti cose:
Integer.parseInt("1");
/ ok
Integer.parseInt("-1");
// ok
Integer.parseInt("+1");
// ok
Integer.parseInt(" 1");
// Exception (spazio vuoto)
Integer.parseInt("2147483648");
// Exception (Integer è limitato a valore massimo di 2.147.483.647)
Integer.parseInt("1.1");
// Eccezione (_ /. o , o qualsiasi altra cosa non consentita)
Integer.parseInt("");
// Exception (non 0 o qualcosa)
Esiste un solo tipo di eccezione: NumberFormatException
Ho una soluzione, ma non so quanto sia efficace. Ma funziona bene, e penso che potresti migliorarlo. D'altra parte, ho fatto un paio di test con JUnit che passo correttamente. Ho allegato la funzione e il test:
static public Integer str2Int(String str) {
Integer result = null;
if (null == str || 0 == str.length()) {
return null;
}
try {
result = Integer.parseInt(str);
}
catch (NumberFormatException e) {
String negativeMode = "";
if(str.indexOf('-') != -1)
negativeMode = "-";
str = str.replaceAll("-", "" );
if (str.indexOf('.') != -1) {
str = str.substring(0, str.indexOf('.'));
if (str.length() == 0) {
return (Integer)0;
}
}
String strNum = str.replaceAll("[^\\d]", "" );
if (0 == strNum.length()) {
return null;
}
result = Integer.parseInt(negativeMode + strNum);
}
return result;
}
Test con JUnit:
@Test
public void testStr2Int() {
assertEquals("is numeric", (Integer)(-5), Helper.str2Int("-5"));
assertEquals("is numeric", (Integer)50, Helper.str2Int("50.00"));
assertEquals("is numeric", (Integer)20, Helper.str2Int("$ 20.90"));
assertEquals("is numeric", (Integer)5, Helper.str2Int(" 5.321"));
assertEquals("is numeric", (Integer)1000, Helper.str2Int("1,000.50"));
assertEquals("is numeric", (Integer)0, Helper.str2Int("0.50"));
assertEquals("is numeric", (Integer)0, Helper.str2Int(".50"));
assertEquals("is numeric", (Integer)0, Helper.str2Int("-.10"));
assertEquals("is numeric", (Integer)Integer.MAX_VALUE, Helper.str2Int(""+Integer.MAX_VALUE));
assertEquals("is numeric", (Integer)Integer.MIN_VALUE, Helper.str2Int(""+Integer.MIN_VALUE));
assertEquals("Not
is numeric", null, Helper.str2Int("czv.,xcvsa"));
/**
* Dynamic test
*/
for(Integer num = 0; num < 1000; num++) {
for(int spaces = 1; spaces < 6; spaces++) {
String numStr = String.format("%0"+spaces+"d", num);
Integer numNeg = num * -1;
assertEquals(numStr + ": is numeric", num, Helper.str2Int(numStr));
assertEquals(numNeg + ": is numeric", numNeg, Helper.str2Int("- " + numStr));
}
}
}
Solo per divertimento: puoi usare Optional
di Java 8 per convertire un String
in un Integer
:
String str = "123";
Integer value = Optional.of(str).map(Integer::valueOf).get();
// Will return the integer value of the specified string, or it
// will throw an NPE when str is null.
value = Optional.ofNullable(str).map(Integer::valueOf).orElse(-1);
// Will do the same as the code above, except it will return -1
// when srt is null, instead of throwing an NPE.
Qui combiniamo solo Integer.valueOf
e Optinal
. Probabilmente potrebbero esserci situazioni in cui ciò è utile, ad esempio quando si desidera evitare i controlli nulli. Il codice Pre Java 8 sarà simile al seguente:
Integer value = (str == null) ? -1 : Integer.parseInt(str);
Guava ha tryParse (String) , che restituisce null
se la stringa non può essere analizzata, ad esempio:
Integer fooInt = Ints.tryParse(fooString);
if (fooInt != null) {
...
}
Puoi anche iniziare rimuovendo tutti i caratteri non numerici e quindi analizzando l'int:
string mystr = mystr.replaceAll( "[^\\d]", "" );
int number= Integer.parseInt(mystr);
Ma sappi che funziona solo per numeri non negativi.
Oltre a queste risposte sopra, vorrei aggiungere diverse funzioni:
public static int parseIntOrDefault(String value, int defaultValue) {
int result = defaultValue;
try {
result = Integer.parseInt(value);
} catch (Exception e) {
}
return result;
}
public static int parseIntOrDefault(String value, int beginIndex, int defaultValue) {
int result = defaultValue;
try {
String stringValue = value.substring(beginIndex);
result = Integer.parseInt(stringValue);
} catch (Exception e) {
}
return result;
}
public static int parseIntOrDefault(String value, int beginIndex, int endIndex, int defaultValue) {
int result = defaultValue;
try {
String stringValue = value.substring(beginIndex, endIndex);
result = Integer.parseInt(stringValue);
} catch (Exception e) {
}
return result;
}
E qui ci sono risultati mentre li esegui:
public static void main(String[] args) {
System.out.println(parseIntOrDefault("123", 0)); // 123
System.out.println(parseIntOrDefault("aaa", 0)); // 0
System.out.println(parseIntOrDefault("aaa456", 3, 0)); // 456
System.out.println(parseIntOrDefault("aaa789bbb", 3, 6, 0)); // 789
}
Nella programmazione delle competizioni, dove si è certi che il numero sarà sempre un numero intero valido, sarà possibile scrivere il proprio metodo per analizzare l'input. Questo salterà tutti i codici relativi alla validazione (dato che non ne hai bisogno) e sarà un po 'più efficiente.
Per intero positivo valido:
private static int parseInt(String str) {
int i, n = 0;
for (i = 0; i < str.length(); i++) {
n *= 10;
n += str.charAt(i) - 48;
}
return n;
}
Per i numeri interi sia positivi che negativi:
private static int parseInt(String str) {
int i=0, n=0, sign=1;
if(str.charAt(0) == '-') {
i=1;
sign=-1;
}
for(; i<str.length(); i++) {
n*=10;
n+=str.charAt(i)-48;
}
return sign*n;
}
Se ti aspetti uno spazio prima o dopo questi numeri, Assicurati di fare un str = str.trim()
prima di procedere ulteriormente.
Come accennato Apache Commons NumberUtils
può farlo. Quale ritorno 0
se non può convertire string in int.
Puoi anche definire il tuo valore predefinito.
NumberUtils.toInt(String str, int defaultValue)
esempio:
NumberUtils.toInt("3244", 1) = 3244
NumberUtils.toInt("", 1) = 1
NumberUtils.toInt(null, 5) = 5
NumberUtils.toInt("Hi", 6) = 6
NumberUtils.toInt(" 32 ", 1) = 1 //space in numbers are not allowed
NumberUtils.toInt(StringUtils.trimToEmpty( " 32 ",1)) = 32;
Puoi usare questo codice anche con alcune precauzioni.
Opzione n. 1: gestire l'eccezione in modo esplicito, ad esempio, mostrando una finestra di dialogo e quindi interrompere l'esecuzione del flusso di lavoro corrente. Per esempio:
try
{
String stringValue = "1234";
// From String to Integer
int integerValue = Integer.valueOf(stringValue);
// Or
int integerValue = Integer.ParseInt(stringValue);
// Now from integer to back into string
stringValue = String.valueOf(integerValue);
}
catch (NumberFormatException ex) {
//JOptionPane.showMessageDialog(frame, "Invalid input string!");
System.out.println("Invalid input string!");
return;
}
Opzione 2: reimpostare la variabile interessata se il flusso di esecuzione può continuare in caso di eccezione. Ad esempio, con alcune modifiche nel blocco catch
catch (NumberFormatException ex) {
integerValue = 0;
}
Usare una costante di stringa per il confronto o qualsiasi tipo di calcolo è sempre una buona idea, perché una costante non restituisce mai un valore nullo.
Puoi usare new Scanner("1244").nextInt()
. Oppure chiedi se esiste anche un int: new Scanner("1244").hasNextInt()
int foo=Integer.parseInt("1234");
Assicurarsi che non ci siano dati non numerici nella stringa.
Per la stringa normale puoi usare:
int number = Integer.parseInt("1234");
Per il generatore di stringhe e il buffer delle stringhe puoi usare:
Integer.parseInt(myBuilderOrBuffer.toString());
Semplicemente puoi provare questo:
Integer.parseInt(your_string);
per convertire un String
in int
Double.parseDouble(your_string);
per convertire un String
in double
String str = "8955";
int q = Integer.parseInt(str);
System.out.println("Output>>> " + q); // Output: 8955
String str = "89.55";
double q = Double.parseDouble(str);
System.out.println("Output>>> " + q); // Output: 89.55
Eccoci qui
String str="1234";
int number = Integer.parseInt(str);
print number;//1234
Sono un po 'sorpreso dal fatto che nessuno abbia menzionato il costruttore Integer che prende String come parametro.
Quindi, ecco:
String myString = "1234";
int i1 = new Integer(myString);
Ovviamente, la funzione di costruzione restituirà il tipo Integer
e l'operazione di annullamento della conversione convertirà il valore in int
.
È importante menzionare
Questo costruttore chiama il metodo parseInt
.
public Integer(String var1) throws NumberFormatException {
this.value = parseInt(var1, 10);
}
Usa Integer.parseInt () e inseriscilo in un blocco try...catch
per gestire eventuali errori nel caso in cui venga inserito un carattere non numerico, ad esempio,
private void ConvertToInt(){
String string = txtString.getText();
try{
int integerValue=Integer.parseInt(string);
System.out.println(integerValue);
}
catch(Exception e){
JOptionPane.showMessageDialog(
"Error converting string to integer\n" + e.toString,
"Error",
JOptionPane.ERROR_MESSAGE);
}
}
Un metodo è parseInt (String) restituisce un int primitivo
String number = "10";
int result = Integer.parseInt(number);
System.out.println(result);
Il secondo metodo è valueOf (String) restituisce un nuovo oggetto Integer ().
String number = "10";
Integer result = Integer.valueOf(number);
System.out.println(result);
Questo è il programma completo con tutte le condizioni positive, negative senza usare la libreria
import Java.util.Scanner;
public class StringToInt {
public static void main(String args[]) {
String inputString;
Scanner s = new Scanner(System.in);
inputString = s.nextLine();
if (!inputString.matches("([+-]?([0-9]*[.])?[0-9]+)")) {
System.out.println("Not a Number");
} else {
Double result2 = getNumber(inputString);
System.out.println("result = " + result2);
}
}
public static Double getNumber(String number) {
Double result = 0.0;
Double beforeDecimal = 0.0;
Double afterDecimal = 0.0;
Double afterDecimalCount = 0.0;
int signBit = 1;
boolean flag = false;
int count = number.length();
if (number.charAt(0) == '-') {
signBit = -1;
flag = true;
} else if (number.charAt(0) == '+') {
flag = true;
}
for (int i = 0; i < count; i++) {
if (flag && i == 0) {
continue;
}
if (afterDecimalCount == 0.0) {
if (number.charAt(i) - '.' == 0) {
afterDecimalCount++;
} else {
beforeDecimal = beforeDecimal * 10 + (number.charAt(i) - '0');
}
} else {
afterDecimal = afterDecimal * 10 + number.charAt(i) - ('0');
afterDecimalCount = afterDecimalCount * 10;
}
}
if (afterDecimalCount != 0.0) {
afterDecimal = afterDecimal / afterDecimalCount;
result = beforeDecimal + afterDecimal;
} else {
result = beforeDecimal;
}
return result * signBit;
}
}
Integer.parseInt(myString);
: utilizzo della classe wrapper
Può essere fatto in 5 modi:
import com.google.common.primitives.Ints;
import org.Apache.commons.lang.math.NumberUtils;
1) Utilizzando Ints.tryParse
:
String number = "999";
int result = Ints.tryParse(number);
2) Utilizzando NumberUtils.createInteger
:
String number = "999";
Integer result = NumberUtils.createInteger(number);
3) Utilizzando NumberUtils.toInt
:
String number = "999";
int result = NumberUtils.toInt(number);
4) Utilizzando Integer.valueOf
:
String number = "999";
Integer result = Integer.valueOf(number);
5) Utilizzando Integer.parseInt
:
String number = "999";
int result = Integer.parseInt(number);
A proposito, tieni presente che se la stringa è nullo, la chiamata:
int i = Integer.parseInt(null);
genera NumberFormatException, non NullPointerException.
Potresti usare uno dei seguenti:
Integer.parseInt(s)
Integer.parseInt(s, radix)
Integer.parseInt(s, beginIndex, endIndex, radix)
Integer.parseUnsignedInt(s)
Integer.parseUnsignedInt(s, radix)
Integer.parseUnsignedInt(s, beginIndex, endIndex, radix)
Integer.valueOf(s)
Integer.valueOf(s, radix)
Integer.decode(s)
NumberUtils.toInt(s)
NumberUtils.toInt(s, defaultValue)
importare Java.util. *;
strToint di classe pubblica {
public static void main(String[] args){
String str = "123";
byte barr[] = str.getBytes();
System.out.println(Arrays.toString(barr));
int result=0;
for(int i=0;i<barr.length;i++){
//System.out.print(barr[i]+" ");
int ii = barr[i];
char a = (char)ii;
int no = Character.getNumericValue(a);
result=result*10+no;
System.out.println(result);
}
System.out.println("result:"+result);
}
}
public static int parseInt (String s) genera NumberFormatException
puoi usare Integer.parseInt()
per convertire una stringa in int.
convertire una stringa 20 in una primitiva int.
String n = "20";
int r = Integer.parseInt(n);//returns a primitive int
System.out.println(r);
Output-20
se la stringa non contiene un numero intero parsabile. verrà lanciato NumberFormatException
String n = "20I";// throwns NumberFormatException
int r = Integer.parseInt(n);
System.out.println(r);
public static Intero valueOf (String s) genera NumberFormatException
puoi usare Integer.valueOf()
, in questo restituirà un oggetto Integer.
String n = "20";
Integer r = Integer.valueOf(n); //returns a new Integer() object.
System.out.println(r);
Output-20
References https://docs.Oracle.com/en/
Alcuni dei modi per convertire String
in Int
sono i seguenti:
puoi usare Integer.parseInt()
:
String test = "4568"; int new = Integer.parseInt(test);
inoltre puoi usare Integer.valueOf()
:
String test = "4568"; int new =Integer.parseInt(test);
Convertire una stringa in un numero intero con il metodo parseInt
della classe Java Integer. Il metodo parseInt
è di convertire la stringa in un int e genera un NumberFormatException
se la stringa non può essere convertita in un tipo int.
Affrontando l'eccezione che può lanciare, usa questo:
int i = Integer.parseInt(myString);
Se la stringa indicata dalla variabile myString
è un numero intero valido come “1234”, “200”, “1”,
e sarà convertita in un int Java. Se fallisce per qualsiasi motivo, la modifica può generare un NumberFormatException
, quindi il codice dovrebbe essere un po 'più lungo per tener conto di ciò.
Ex. Java String
a int
metodo di conversione, controllo per un possibile NumberFormatException
public class JavaStringToIntExample
{
public static void main (String[] args)
{
// String s = "test"; // use this if you want to test the exception below
String s = "1234";
try
{
// the String to int conversion happens here
int i = Integer.parseInt(s.trim());
// print out the value after the conversion
System.out.println("int i = " + i);
}
catch (NumberFormatException nfe)
{
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
}
Se il tentativo di modifica fallisce - nel caso in cui, se si può provare a convertire il test di stringa Java in un int - il processo Integer parseInt
genererà un NumberFormatException
, che è necessario gestire in un blocco try/catch.
È possibile utilizzare il metodo parseInt
String SrNumber="5790";
int extractNumber = Integer.parseInt(SrNumber);
System.out.println(extractNumber);//Result will be --5790
Algoritmo personalizzato:
public static int toInt(String value) {
int output = 0;
boolean isFirstCharacter = true;
boolean isNegativeNumber = false;
byte bytes[] = value.getBytes();
for (int i = 0; i < bytes.length; i++) {
char c = (char) bytes[i];
if (!Character.isDigit(c)) {
isNegativeNumber = (c == '-');
if (!(isFirstCharacter && (isNegativeNumber || c == '+'))) {
throw new NumberFormatException("For input string \"" + value + "\"");
}
} else {
int number = Character.getNumericValue(c);
output = output * 10 + number;
}
isFirstCharacter = false;
}
if (isNegativeNumber) output *= -1;
return output;
}
un'altra soluzione: (usa il metodo string charAt invece di convertire la stringa nell'array di byte):
public static int toInt(String value) {
int output = 0;
boolean isFirstCharacter = true;
boolean isNegativeNumber = false;
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (!Character.isDigit(c)) {
isNegativeNumber = (c == '-');
if (!(isFirstCharacter && (isNegativeNumber || c == '+'))) {
throw new NumberFormatException("For input string \"" + value + "\"");
}
} else {
int number = Character.getNumericValue(c);
output = output * 10 + number;
}
isFirstCharacter = false;
}
if (isNegativeNumber) output *= -1;
return output;
}
Esempi:
int number1 = toInt("20");
int number2 = toInt("-20");
int number3 = toInt("+20");
System.out.println("Numbers = " + number1 + ", " + number2 + ", " + number3);
try {
toInt("20 Hadi");
} catch (NumberFormatException e) {
System.out.println("Error: " + e.getMessage());
}
Utilizzando il metodo: Integer.parseInt(String s)
String s = "123";
int n = Integer.parseInt(s);
Usa Integer.parseInt()
, questo ti aiuterà ad analizzare il tuo valore di stringa su int.
Esempio:
String str = "2017";
int i = Integer.parseInt(str);
System.out.println(i);
uscita:. .__ 2017
Usa questo metodo:
public int ConvertStringToInt(String number)
{
int num = 0;
try
{
int newNumber = Integer.ParseInt(number);
num = newNumber;
}
catch(Exception ex)
{
num = 0;
Log.i("Console",ex.toString);
}
return num;
}
Prova questo codice con diversi input di String
:
String a = "10";
String a = "10ssda";
String a = null;
String a = "12102";
if(null != a) {
try {
int x = Integer.ParseInt(a.trim());
Integer y = Integer.valueOf(a.trim());
// It will throw a NumberFormatException in case of invalid string like ("10ssda" or "123 212") so, put this code into try catch
} catch(NumberFormatException ex) {
// ex.getMessage();
}
}
Ho scritto questo metodo veloce per analizzare un input di stringa in int o long. È più veloce dell'attuale JDK 11 Integer.parseInt o Long.parseLong. Sebbene tu abbia richiesto solo int, includevo anche il parser lungo. Il parser di codice qui sotto richiede che il metodo del parser deve essere piccolo per poter funzionare rapidamente. Una versione alternativa è sotto il codice di test. La versione alternativa è piuttosto veloce e non dipende dalle dimensioni della classe.
Questo controllo di classe per l'overflow e puoi personalizzare il codice per adattarlo alle tue esigenze. Una stringa vuota produrrà 0 con il mio metodo ma è intenzionale. Puoi cambiarlo per adattare il tuo caso o usarlo così com'è.
Questa è solo la parte della classe in cui sono necessari parseInt e parseLong. Si noti che questo riguarda solo i numeri di base 10.
Il codice di test per il parser int è sotto il codice qui sotto.
/*
* Copyright 2019 Khang Hoang Nguyen
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
* @author: Khang Hoang Nguyen - [email protected]
**/
final class faiNumber{
private static final long[] longpow = {0L, 1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L, 1000000000L,
10000000000L, 100000000000L, 1000000000000L, 10000000000000L, 100000000000000L,
1000000000000000L, 10000000000000000L, 100000000000000000L, 1000000000000000000L,
};
private static final int[] intpow = { 0, 1, 10, 100, 1000, 10000,
100000, 1000000, 10000000, 100000000, 1000000000
};
/**
* parseLong(String str) parse a String into Long.
* All errors throw by this method is NumberFormatException.
* Better errors can be made to tailor to each use case.
**/
public static long parseLong(final String str) {
final int length = str.length();
if ( length == 0 ) return 0L;
char c1 = str.charAt(0); int start;
if ( c1 == '-' || c1 == '+' ){
if ( length == 1 ) throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );
start = 1;
} else {
start = 0;
}
/*
* Note: if length > 19, possible scenario is to run through the string
* to check whether the string contains only valid digits.
* If the check had only valid digits then a negative sign meant underflow, else, overflow.
*/
if ( length - start > 19 ) throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );
long c;
long out = 0L;
for ( ; start < length; start++){
c = (str.charAt(start) ^ '0');
if ( c > 9L ) throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );
out += c * longpow[length - start];
}
if ( c1 == '-' ){
out = ~out + 1L;
// if out > 0 number underflow(supposed to be negative).
if ( out > 0L ) throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );
return out;
}
// if out < 0 number overflow(supposed to be positive).
if ( out < 0L ) throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );
return out;
}
/**
* parseInt(String str) parse a string into an int.
* return 0 if string is empty.
**/
public static int parseInt(final String str) {
final int length = str.length();
if ( length == 0 ) return 0;
char c1 = str.charAt(0); int start;
if ( c1 == '-' || c1 == '+' ){
if ( length == 1 ) throw new NumberFormatException( String.format("Not a valid integer value. Input '%s'.", str) );
start = 1;
} else {
start = 0;
}
int out = 0; int c;
int runlen = length - start;
if ( runlen > 9 ) {
if ( runlen > 10 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
c = (str.charAt(start) ^ '0'); // <- Any number from 0 - 255 ^ 48 will yield greater than 9 except 48 - 57
if ( c > 9 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
if ( c > 2 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
out += c * intpow[length - start++];
}
for ( ; start < length; start++){
c = (str.charAt(start) ^ '0');
if ( c > 9 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
out += c * intpow[length - start];
}
if ( c1 == '-' ){
out = ~out + 1;
if ( out > 0 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
return out;
}
if ( out < 0 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
return out;
}
}
Test codice sezione. Questo dovrebbe richiedere circa 200 secondi o giù di lì.
// Int Number Parser Test;
long start = System.currentTimeMillis();
System.out.println("INT PARSER TEST");
for (int i = Integer.MIN_VALUE; i != Integer.MAX_VALUE; i++){
if( faiNumber.parseInt(""+i) != i ) System.out.println("Wrong");
if ( i == 0 ) System.out.println("HalfWay Done");
}
if( faiNumber.parseInt(""+Integer.MAX_VALUE) != Integer.MAX_VALUE ) System.out.println("Wrong");
long end = System.currentTimeMillis();
long result = (end - start);
System.out.println(result);
// INT PARSER END */
Un metodo alternativo che è anche molto veloce. Si noti che l'array di int pow non viene usato ma un'ottimizzazione matematica di moltiplicare per 10 lo spostamento dei bit.
public static int parseInt(final String str) {
final int length = str.length();
if ( length == 0 ) return 0;
char c1 = str.charAt(0); int start;
if ( c1 == '-' || c1 == '+' ){
if ( length == 1 ) throw new NumberFormatException( String.format("Not a valid integer value. Input '%s'.", str) );
start = 1;
} else {
start = 0;
}
int out = 0; int c;
while( start < length && str.charAt(start) == '0' ) start++; // <-- This to disregard leading 0, can be removed if you know exactly your source does not have leading zeroes.
int runlen = length - start;
if ( runlen > 9 ) {
if ( runlen > 10 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
c = (str.charAt(start++) ^ '0'); // <- Any number from 0 - 255 ^ 48 will yield greater than 9 except 48 - 57
if ( c > 9 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
if ( c > 2 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
out = (out << 1) + (out << 3) + c; // <- alternatively this can just be out = c or c above can just be out;
}
for ( ; start < length; start++){
c = (str.charAt(start) ^ '0');
if ( c > 9 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
out = (out << 1) + (out << 3) + c;
}
if ( c1 == '-' ){
out = ~out + 1;
if ( out > 0 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
return out;
}
if ( out < 0 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
return out;
}