Loop para sempre
-
21-09-2019 - |
Pergunta
Estou tentando fazer uma exceção, mas por algum motivo não está me dando a opção de escrever meu arquivo de scanner:
Não sei como usar o BufferredReader, é por isso que estou usando isso. Alguma pista?
Aqui está minha aula padrão com meu 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);
}
}
E aqui está minha aula principal com a exceção sendo implementada com um loop:
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;
}
}
Se alguém tiver alguma idéia de como fazer loop de maneira diferente, eu sou todos ouvidos.
Solução 2
Decidi me livrar da classe de método e apenas colocar o método na área de exceção de tentativa.
Usou uma linha .next após o scanner e parece fixo.
isso parece ok?
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;
}
}
Outras dicas
Defina o erro false antes da a acção. Dessa forma, você tem a condição de saída correta se o usuário acertar.
error = false;
zack.findNumbers();
Você faz um loop enquanto 'erro' A variável tem valor 'verdadeiro'. No entanto, torna -se 'verdadeiro' Somente quando é jogado (ou seja, quando 'truque' bloco é executado). O fluxo de controle não atinge.