[英]Display Error if Number System input is invalid
我想使用 Java (我已经尝试过)将数字系统编码为 ASCII 转换器但我想 output 如果输入错误而不是退出程序并显示错误,则“无效”。 希望这是可能的。
我已经得到了转换后的输出。 我只想输入一个“无效”output,以防我选择的数字系统和输入不匹配。
do{
opt=displayMainMenu();
switch(opt){
case 1:
binary=getBinary();
System.out.println("\n\tASCII Character: "+ (char)binary);
in.readLine();
break;
case 2:
octal=getOctal();
System.out.println("\n\tASCII Character: "+(char)octal);
in.readLine();
break;
case 3:
decimal=getDecimal();
System.out.println("\n\tASCII Character: "+(char)decimal);
in.readLine();
break;
//case 4: still don't have Hexadecimal since I find it difficult. Sorry
case 5:
System.out.println("\f\n\tGood Bye!");
break;
default:
System.out.print("\n\tInvalid Option.");
in.readLine();
}
}while(opt!=5);
//我只发一个
public static int getOctal() throws Exception{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Scanner s=new Scanner(System.in);
System.out.println("\f\n\t\t- Octal -\n");
System.out.print("\n\tInput Octal Number: ");
String n=s.nextLine();
int oct = Integer.parseInt(n,8);
return oct;
}
样本输入:
选择一个数字系统:2 //八进制到 ASCII
输入八进制数:3A //十六进制
Output:无效。
选择一个数字系统:2 //八进制到 ASCII
输入八进制数:041//正确
Output:ASCII是!
如果你问我,我认为你的getOctal()方法真的应该被称为getIntegerFromOctal() 。 但是,嘿...也许这只是我。
很多人所做的是将解析包装在try/catch块中并捕获任何错误,如下所示:
public static int getIntegerFromOctal() {
Scanner s = new Scanner(System.in);
String ls = System.lineSeparator();
System.out.println(ls + " - Octal -");
while (true) {
System.out.print("Input Octal Number: ");
String n = s.nextLine();
int oct = 0;
try {
oct = Integer.parseInt(n, 8);
return oct;
}
catch (NumberFormatException ex) {
System.err.print("Invalid Octal Value Supplied! Try again..." + ls + ls);
}
}
}
另一种方法是结合使用正则表达式(RegEx) 和String#matches()方法:
public static int getIntegerFromOctal() {
Scanner s = new Scanner(System.in);
String ls = System.lineSeparator();
System.out.println(ls + " - Octal -");
while (true) {
System.out.print("Input Octal Number: ");
String n = s.nextLine();
int oct = 0;
/* The String#matches() method is used here with a
regex that ensures that only digits from 0 to 7
(octal digits) are supplied. If you want to also
ensure Integer Literal where the integer value
supplied starts with a 0 then use: "^0[0-7]+$" */
if (!n.matches("^[0-7]+$")) {
System.err.print("Invalid Octal Value (" + n + ") Supplied! Try again..." + ls + ls);
continue;
}
oct = Integer.parseInt(n, 8);
return oct;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.