Pregunta

Para un programa que estoy escribiendo, necesito pedirle a un usuario un número entero entre 1 y 8. He intentado varias formas (más limpias) de hacerlo, pero ninguna funcionó, así que me queda esto:

    int x = 0;
    while (x < 1 || x > 8)
    {   
        System.out.print("Please enter integer  (1-8): ");

        try
        {
            x = Integer.parseInt(inputScanner.next());
        }
        catch(NumberFormatException e)
        {
            x = 0;
        }
    }

Donde inputScanner es un escáner. ¿Seguramente hay una mejor manera?

¿Fue útil?

Solución

Escáner hace expresiones regulares, ¿verdad? ¿Por qué no comprobar si coincide con " ^ [1-8] $ " primero?

Otros consejos

Usar nextInt () ya es una mejora en comparación con simplemente usar el método next (). Y antes de eso, puede usar hasNextInt () para evitar tener todo este grupo de excepciones inútiles.

Resultando en algo como esto:

int x = 0;
do {
  System.out.print("Please...");
  if(scanner.hasNextInt()) x = scanner.nextInt();
  else scanner.next();
} while (x < 1 || x > 8);

Tuve que hacer una calculadora de interfaz gráfica (solo funciona con números enteros), y el problema era que las pruebas no permitieron que se lanzaran excepciones si la entrada no era Entero. Entonces no pude usar

try { int x = Integer.parseInt(input)} catch (Exception e) {dosomethingelse}

Debido a que los programas Java generalmente tratan una entrada a un JTextField como una cadena Usé esto:

if (input.matches("[1-9][0-9]*"){ // String.matches() returns boolean
   goodforyou
} else {
   dosomethingelse
}

// this checks if the input's (type String) character sequence matches
// the given parameter. The [1-9] means that the first char is a Digit
// between 1 and 9 (because the input should be an Integer can't be 0)
// the * after [0-9] means that after the first char there can be 0 - infinity
// characters between digits 0-9

espero que esto ayude :)

Apache Commons es tu amigo. Ver NumberUtils.toInt (String, int)

String input;
int number;

while (inputScanner.hasNextLine())
{
    input = inputScanner.nextLine();

    if (input.equals("quit")) { System.exit(0); }
    else
    {
        //If you don't want to put your code in here, make an event handler
        //that gets called from this spot with the input passed in
        try
        {
            number = Integer.parseInt(input);
            if ((number < 1) || (number > 8))
            { System.out.print("Please choose 1-8: "); }
            else { /* Do stuff */ }
        }
        catch (NumberFormatException e) { number = 0; }
    }
}

Siempre me gusta tirar de la cadena completa para que pueda estar seguro de que el usuario presionó el botón Enter. Si solo usa inputScanner.nextInt () , puede poner dos int s en una línea y se abrirá una, luego la otra.

Código de ejemplo:

int x;
Scanner in = new Scanner(System.in);
System.out.println("Enter integer value: ");
x = in.nextInt();

Una matriz también se puede utilizar para almacenar el número entero.

Podría intentar algo como esto:

Scanner cin = new Scanner(System.in);
int s = 0;    
boolean v = false;
while(!v){
    System.out.print("Input an integer >= 1: ");

    try {    
        s = cin.nextInt();
        if(s >= 1) v = true;
        else System.out.println("Please input an integer value >= 1.");
    } 
    catch(InputMismatchException e) {
        System.out.println("Caught: InputMismatchException -- Please input an integer value >= 1. ");
        cin.next();
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top