Come posso sapere se un numero intero Java è nullo?
Domanda
Saluti,
Sto cercando di convalidare se il mio numero intero è null. In tal caso, devo richiedere all'utente di inserire un valore. Il mio background è Perl, quindi il mio primo tentativo è simile al seguente:
int startIn = Integer.parseInt (startField.getText());
if (startIn) {
JOptionPane.showMessageDialog(null,
"You must enter a number between 0-16.","Input Error",
JOptionPane.ERROR_MESSAGE);
}
Questo non funziona, poiché Java si aspetta una logica booleana.
In Perl, posso usare " esiste " per verificare se gli elementi hash / array contengono dati con:
@items = ("one", "two", "three");
#@items = ();
if (exists($items[0])) {
print "Something in \@items.\n";
}
else {
print "Nothing in \@items!\n";
}
C'è un modo per farlo in Java? Grazie per il tuo aiuto!
Geremia
P.S. Perl esiste informazioni
Soluzione
parseInt ()
genererà un'eccezione se l'analisi non può essere completata correttamente. Puoi invece usare Integer
, il tipo di oggetto corrispondente, che rende le cose un po 'più pulite. Quindi probabilmente vuoi qualcosa di più vicino a:
Integer s = null;
try {
s = Integer.valueOf(startField.getText());
}
catch (NumberFormatException e) {
// ...
}
if (s != null) { ... }
Attenzione se decidi di usare parseInt ()
! parseInt ()
non supporta una buona internazionalizzazione, quindi devi saltare ancora più cerchi:
try {
NumberFormat nf = NumberFormat.getIntegerInstance(locale);
nf.setParseIntegerOnly(true);
nf.setMaximumIntegerDigits(9); // Or whatever you'd like to max out at.
// Start parsing from the beginning.
ParsePosition p = new ParsePosition(0);
int val = format.parse(str, p).intValue();
if (p.getIndex() != str.length()) {
// There's some stuff after all the digits are done being processed.
}
// Work with the processed value here.
} catch (java.text.ParseFormatException exc) {
// Something blew up in the parsing.
}
Altri suggerimenti
Prova questo:
Integer startIn = null;
try {
startIn = Integer.valueOf(startField.getText());
} catch (NumberFormatException e) {
.
.
.
}
if (startIn == null) {
// Prompt for value...
}
int
sono tipi di valore; non possono mai essere null
. Al contrario, se l'analisi non è riuscita, parseInt
genererà un NumberFormatException
che devi catturare.
Non esiste esiste
per un SCALAR in Perl, comunque. La via del Perl è
defined( $x )
e Java equivalente è
anInteger != null
Quelli sono gli equivalenti.
exists $hash{key}
È come Java
map.containsKey( "key" )
Dal tuo esempio, penso che tu stia cercando
if (startIn! = null) {...
Per me usare semplicemente il metodo Integer.toString () funziona bene per me. Puoi convertirlo se vuoi solo se è nullo. Esempio seguente:
private void setCarColor(int redIn, int blueIn, int greenIn)
{
//Integer s = null;
if (Integer.toString(redIn) == null || Integer.toString(blueIn) == null || Integer.toString(greenIn) == null )
Non credo che tu possa usare " esiste " su un numero intero in Perl, solo sulle raccolte. Puoi fare un esempio di cosa intendi in Perl che corrisponde al tuo esempio in Java.
Data un'espressione che specifica un elemento hash o un elemento array, restituisce true se l'elemento specificato nell'hash o nell'array è mai stato inizializzato, anche se il valore corrispondente non è definito.
Questo indica che si applica solo agli elementi hash o array!
Questo dovrebbe aiutare.
Integer startIn = null;
// (optional below but a good practice, to prevent errors.)
boolean dontContinue = false;
try {
Integer.parseInt (startField.getText());
} catch (NumberFormatException e){
e.printStackTrace();
}
// in java = assigns a boolean in if statements oddly.
// Thus double equal must be used. So if startIn is null, display the message
if (startIn == null) {
JOptionPane.showMessageDialog(null,
"You must enter a number between 0-16.","Input Error",
JOptionPane.ERROR_MESSAGE);
}
// (again optional)
if (dontContinue == true) {
//Do-some-error-fix
}