Im tratando de avisar al usuario para mantener el formato inputing valor correcto hasta su hecho correctamente. Quiero mostrar al usuario que si él / ella ha escrito en un formato incorrecto (número de valores), él / ella debe tratar de nuevo y el sistema pedirá al usuario que los nuevos valores de entrada. ¿Cómo lo hago con el siguiente código de abajo?
Y es la declaración, mientras que en la parte inferior válida (correctamente escrito)? Al igual que si la tampoco provocó una excepción, parada de "hacer: ing"
PS, sé que mi código de abajo se ve horrible, ya que soy un principiante simple y no saben cómo código de formato correctamente
public class PersonTidbok {
public static void main(String[] args){
Scanner console = new Scanner (System.in);
System.out.print ("Welcome to your interface, please select of the following: " +
"\nP, T, L, S, A, Q");
choice = console.next().charAt(0);
switch (choice){
case P:
do{
System.out.print (" enter persnr in the format of (YYYYMMDD));
try{
persnr = console.nextInt();
if ( persnr.length != 8);
throw new FormatException();
}
catch (FormatException exception){
System.out.println(exception + "You printed wrong format, try again"));
}
}
while (!FormatException);
}
}
Hacerlo de la siguiente manera:
import java.util.Scanner;
public class PersonTidbok {
public static void main(String[] argv) {
Scanner console = new Scanner(System.in);
boolean valid;
char choice = '\0';
String persnr;
do {
valid = true;
System.out.print("Welcome to your interface, please select of the following (P, T, L, S, A, Q): ");
String input = console.nextLine();
if (input.length() != 1) {
System.out.println("Invalid input. Try again.");
valid = false;
}
choice = input.charAt(0);
} while (!valid);
switch (choice) {
case 'P':
do {
valid = true;
System.out.print("Enter persnr in the format of (YYYYMMDD): ");
try {
persnr = console.nextLine();
if (!persnr.matches("[1-9]{1}[0-9]{7}")) {
throw new IllegalArgumentException("You printed wrong format, try again");
}
System.out.println("Processsing...");
// ...Processing of persnr should go here
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
valid = false;
}
} while (!valid);
break;
default:
System.out.println("Wrong value for choice.");
}
}
}
Un análisis de la muestra:
Welcome to your interface, please select of the following (P, T, L, S, A, Q): a
Wrong value for choice.
Otra muestra de la ejecución:
Welcome to your interface, please select of the following (P, T, L, S, A, Q): PT
Invalid input. Try again.
Welcome to your interface, please select of the following (P, T, L, S, A, Q): P
Enter persnr in the format of (YYYYMMDD): 01234567
You printed wrong format, try again
Enter persnr in the format of (YYYYMMDD): ancdefgh
You printed wrong format, try again
Enter persnr in the format of (YYYYMMDD): 20180912
Processsing...