Un modo più semplice per garantire l'input intero tramite Scanner?
-
19-08-2019 - |
Domanda
Per un programma che sto scrivendo, devo chiedere a un utente un numero intero compreso tra 1 e 8. Ho provato diversi modi (più puliti) di farlo, ma nessuno di loro ha funzionato, quindi mi rimane questo:
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;
}
}
Dove inputScanner
è uno scanner. Sicuramente esiste un modo migliore?
Soluzione
Lo scanner fa espressioni regolari, giusto? Perché non controllare se corrisponde a " ^ [1-8] $ " prima?
Altri suggerimenti
L'uso di nextInt () è già un miglioramento rispetto al semplice utilizzo del metodo next (). E prima, puoi usare hasNextInt () per evitare di avere tutto questo mucchio di inutili eccezioni.
Risultato in qualcosa del genere:
int x = 0;
do {
System.out.print("Please...");
if(scanner.hasNextInt()) x = scanner.nextInt();
else scanner.next();
} while (x < 1 || x > 8);
Ho dovuto fare un calcolatore di interfaccia grafica (funziona solo con numeri interi), e il problema era che i test non consentivano di generare eccezioni se l'input non lo era Numero intero. Quindi non ho potuto usare
try { int x = Integer.parseInt(input)} catch (Exception e) {dosomethingelse}
Poiché i programmi Java generalmente trattano un input di un JTextField come una stringa Ho usato questo:
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
spero che questo aiuti :)
Apache Commons è tuo amico. Vedi 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; }
}
}
Mi piace sempre inserire l'intera stringa in modo da poter essere sicuri che l'utente abbia premuto il pulsante Invio. Se usi semplicemente inputScanner.nextInt ()
puoi mettere due int
su una linea e ne verrà inserita una, quindi l'altra.
Codice di esempio:
int x;
Scanner in = new Scanner(System.in);
System.out.println("Enter integer value: ");
x = in.nextInt();
Un array può anche essere usato per memorizzare l'intero.
Potresti provare qualcosa del genere:
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();
}
}