Pregunta

Saludos,

Estoy intentando validar si mi número entero es nulo. Si es así, necesito pedirle al usuario que ingrese un valor. Mi experiencia es Perl, así que mi primer intento se ve así:

int startIn = Integer.parseInt (startField.getText());

if (startIn) { 
    JOptionPane.showMessageDialog(null,
         "You must enter a number between 0-16.","Input Error",
         JOptionPane.ERROR_MESSAGE);                
}

Esto no funciona, ya que Java espera una lógica booleana.

En Perl, puedo usar "existe". para verificar si los elementos hash / array contienen datos con:

@items = ("one", "two", "three");
#@items = ();

if (exists($items[0])) {
    print "Something in \@items.\n";
}
else {
    print "Nothing in \@items!\n";
}

¿Hay alguna forma de esto en Java? ¡Gracias por tu ayuda!

Jeremías

P.S. Perl existe información.

¿Fue útil?

Solución

parseInt () solo lanzará una excepción si el análisis no puede completarse con éxito. En su lugar, puede usar Integers , el tipo de objeto correspondiente, que hace las cosas un poco más limpias. Entonces, probablemente desee algo más cercano a:

Integer s = null;

try { 
  s = Integer.valueOf(startField.getText());
}
catch (NumberFormatException e) {
  // ...
}

if (s != null) { ... }

¡Cuidado! si decides usar parseInt () ! parseInt () no admite una buena internacionalización, por lo que debe pasar por más aros:

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.
}

Otros consejos

Prueba esto:

Integer startIn = null;

try {
  startIn = Integer.valueOf(startField.getText());
} catch (NumberFormatException e) {
  .
  .
  .
}

if (startIn == null) {
  // Prompt for value...
}

int s son tipos de valores; nunca pueden ser null . En cambio, si falla el análisis, parseInt arrojará una NumberFormatException que necesita capturar.

No hay existe para un SCALAR en Perl, de todos modos. La forma de Perl es

defined( $x ) 

y el Java equivalente es

anInteger != null

Esos son los equivalentes.

exists $hash{key}

Es como el Java

map.containsKey( "key" )

De tu ejemplo, creo que estás buscando

if (startIn! = null) {...

Para mí, usar el método Integer.toString () me funciona muy bien. Puede convertirlo si solo quiere hacerlo muy si es nulo. Ejemplo a continuación:

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 )

No creo que pueda usar " existe " en un entero en Perl, solo en colecciones. ¿Puede dar un ejemplo de lo que quiere decir en Perl que coincide con su ejemplo en Java?

  

Dada una expresión que especifica un elemento hash o elemento de matriz, devuelve verdadero si el elemento especificado en el hash o matriz alguna vez se ha inicializado, incluso si el valor correspondiente no está definido.

¡Esto indica que solo se aplica a los elementos hash o array!

Esto debería ayudar.

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
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top