Foro sobre Java SE > Evaluar int y null
if (leido == null)
¡Ay, ay, ay!, que las comparaciones se hacen con DOS ==, mientras que las asignaciones se hacen con UN =
¡Suspenso en evaluaciones! :D
De todos modos, el compilador no admite que se compare un valor primitivo como int con null, y además el método nextInt devuelve un int, por lo que nunca devuelve un null, sino que puede lanzar una excepción de entre estas tres:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
Código de nextInt:
/**
* Scans the next token of the input as an <tt>int</tt>.
* This method will throw InputMismatchException
* if the next token cannot be translated into a valid int value as
* described below. If the translation is successful, the scanner advances
* past the input that matched.
*
* <p> If the next token matches the Integer regular expression defined
* above then the token is converted into an <tt>int</tt> value as if by
* removing all locale specific prefixes, group separators, and locale
* specific suffixes, then mapping non-ASCII digits into ASCII
* digits via {@link Character#digit Character.digit}, prepending a
* negative sign (-) if the locale specific negative prefixes and suffixes
* were present, and passing the resulting string to
* {@link Integer#parseInt(String, int) Integer.parseInt} with the
* specified radix.
*
* @param radix the radix used to interpret the token as an int value
* @return the <tt>int</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the Integer
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public int nextInt(int radix) {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Integer)
&& this.radix == radix) {
int val = ((Integer)typeCache).intValue();
useTypeCache();
return val;
}
setRadix(radix);
clearCaches();
// Search for next int
try {
String s = next(integerPattern());
if (matcher.group(SIMPLE_GROUP_INDEX) == null)
s = processIntegerToken(s);
return Integer.parseInt(s, radix);
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
Gracias choces, como siempre un lujo tenerte.
String leidoconvertidoa= String.valueOf(leido);
if (leidoconvertidoa == null)
no se evaluar el if (leido = null), obviamente leido es int.
Scanner lector = new Scanner(System.in);
leido = lector.nextInt();
if (leido = null) // ¿como se evalúa esto?
miArray[n] = 99;
else
miArray[n] = leido;
}
Gracias de antemano.