Maneira mais fácil de entrada inteiro garantia através Scanner?
-
19-08-2019 - |
Pergunta
Para um programa que eu estou escrevendo, eu preciso perguntar a um usuário para um número inteiro entre 1 e 8. Eu tentei várias maneiras (limpeza) de fazer isso, mas nenhum deles funcionou, então eu estou à esquerda com isto:
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;
}
}
Onde inputScanner
é um Scanner. Certamente há uma maneira melhor?
Solução
Scanner faz expressões regulares, certo? Por que não verificar se ele corresponde "^ [1-8] $" em primeiro lugar?
Outras dicas
Usando o nextInt () já é uma melhoria comparar simplesmente usando o método next (). E antes disso, você pode usar o hasNextInt () para evitar haing todo esse monte de exceções inúteis.
Resultando em algo como isto:
int x = 0;
do {
System.out.print("Please...");
if(scanner.hasNextInt()) x = scanner.nextInt();
else scanner.next();
} while (x < 1 || x > 8);
Eu tive que fazer uma calculadora interface gráfica (funciona apenas com números inteiros), eo problema foi que, os testes não permitiu quaisquer excepções a ser lançada se a entrada não foi Integer. Então, eu não poderia usar
try { int x = Integer.parseInt(input)} catch (Exception e) {dosomethingelse}
Como os programas Java geralmente tratar uma entrada para um JTextField como uma String Eu usei isso:
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 isso ajude:)
Apache Commons é seu amigo. Veja 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; }
}
}
Eu sempre gosto de puxar a corda completo para que você pode ter certeza que o usuário apertou o botão Enter. Se você usar apenas inputScanner.nextInt()
você pode colocar dois int
s em uma linha e ele vai puxar em um, depois o outro.
código Exemplo:
int x;
Scanner in = new Scanner(System.in);
System.out.println("Enter integer value: ");
x = in.nextInt();
Uma disposição pode também ser utilizada para armazenar o número inteiro.
Você poderia tentar algo como isto:
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();
}
}