bucle para siempre
-
21-09-2019 - |
Pregunta
Estoy tratando de bucle de una excepción, pero por alguna razón no es me da la opción de volver a escribir mi archivo de escáner:
No sé cómo usar BufferedReader así que por eso estoy usando esto. ¿Alguna pista?
Aquí está mi clase estándar con mi método
package arrayExceptionsWithInput;
import java.util.*;
public class GetThoseNumbersBaby {
int firstInt;
int secondInt;
boolean error;
Scanner yourNumbers = new Scanner(System.in);
public void findNumbers()
{
System.out.println(" please enter your first number");
firstInt = yourNumbers.nextInt();
System.out.println(" pleas enter your second number");
secondInt = yourNumbers.nextInt();
int finalInt = (firstInt+secondInt);
System.out.println("total is: " + finalInt);
}
}
Y aquí está mi principal clase con la excepción siendo implementado algunas con un bucle:
package arrayExceptionsWithInput;
import java.util.*;
public class InputException
{
public static void main(String[] args)
{
boolean error = false;
GetThoseNumbersBaby zack = new GetThoseNumbersBaby();
{
do {
try
{
zack.findNumbers();
}
catch(InputMismatchException Q)
{
System.out.println(" one of your integers was incorrect, please try again");
Q.printStackTrace();
error = true;
}
} while (error == true);
}
error = false;
}
}
Si alguien tiene alguna idea sobre la forma de bucle esto de manera diferente soy todo oídos.
Solución 2
i decidió también deshacerse de la clase método y sólo hay que poner el método en el área excepción intentarlo.
utilizado un escáner .nextLine después y parece fijo.
Esto tiene buen aspecto?
package arrayExceptionsWithInput;
import java.util.*;
public class InputException
{
public static void main(String[] args)
{
boolean error = false;
int firstInt;
int secondInt;
Scanner yourNumbers = new Scanner(System.in);
{
do{
try
{
System.out.println(" please enter your first number");
firstInt = yourNumbers.nextInt();
yourNumbers.nextLine();
System.out.println(" pleas enter your second number");
secondInt = yourNumbers.nextInt();
yourNumbers.nextLine();
int finalInt = (firstInt+secondInt);
System.out.println("total is: " + finalInt);
yourNumbers.nextLine();
}
catch(InputMismatchException Q)
{
Q.printStackTrace();
System.out.println(" one of your integers was incorrect, please try again");
error = true;
yourNumbers.nextLine();
}
}while (error == true);
}error = false;
}
}
Otros consejos
Set error false antes la acción. De esa manera usted tiene la condición de salida correcta si el usuario lo hace bien.
error = false;
zack.findNumbers();
bucle while 'error' variable tiene el valor 'verdadero' . Sin embargo, se convierte en 'verdadero' sólo cuando el se lanza (es decir, cuando 'captura' se ejecuta el bloque). flujo de control no lo alcanza.