我试图告诉用户继续输入正确的值格式,直到正确完成为止。我想向用户显示,如果他/她输入了错误的格式(值的数量),则他/她应再试一次,系统将要求用户输入新值。我如何使用下面的代码来做到这一点?
底部的while语句是否有效(正确编写)?就像没有触发异常一样,停止“ do:ing”
PS,我知道下面的代码看起来很糟糕,因为我只是个初学者,不知道如何正确格式化代码
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);
}
}
问题来源:Stack Overflow
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.");
}
}
}
运行示例:
Welcome to your interface, please select of the following (P, T, L, S, A, Q): a
Wrong value for choice.
另一个示例运行:
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...
回答来源:Stack Overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。