自我标记:异常处理try-catch的初尝试
辣鸡小玲的代码
UVA355 The Bases Are Loaded
算法来自于小白菜又菜的C版
AC的代码就长这样:完完全全的C语言,有点丑
import java.util.Scanner;
import java.util.*;
public class Main {
public static int ctoi(char ch) {
if (ch >= '0' && ch <= '9')
return ch - '0';
return ch - 'A' + 10;
}
public static char itoc(long v) {
if (v < 10)
return (char) (v + '0');
return (char) (v + 'A' - 10);
}
public static char itoc(int v) {
if (v < 10)
return (char) (v + '0');
return (char) (v + 'A' - 10);
}
public static void dtob2(long v, int b2) {
if (v > 0) {
dtob2(v / b2, b2);// 震惊!小白菜又菜的算法中居然出现了递归
System.out.printf("%c", itoc(v % b2));
}
}
public static void main(String[] args) {
int base, target;
String s;
Scanner reader = new Scanner(System.in);
while (reader.hasNext()) {
base = reader.nextInt();
target = reader.nextInt();
s = reader.next();
boolean flag=false;
int i,len=s.length();
for(i=0;i<len;i++) {//做非法判断
if(ctoi(s.charAt(i))>=base) {
flag=true;
break;
}
}
if(flag) {
System.out.println(s+" is an illegal base "+base+" number");
continue;
}
long value=0L;
//转换成十进制
for(i=0;i<len;i++) {
value*=base;
value+=ctoi(s.charAt(i));
}
//转换成target进制
System.out.print(s+" base "+base+" = ");
if(value==0L)
System.out.print('0');
else
dtob2(value,target);
System.out.println(" base "+target);
}
}
}
是尝试过用JAVA的各种方法、函数来A这题,连try-catch都编译通过而且过了好多组测试用例了。但是因为有:
FFFFFFFFFF base 16 = 1111111111111111111111111111111111111111 base 2
这样的流氓测试用例(转换成二进制之后超过了int 32位的限制),导致好用的函数没法用。
不得不说try-catch省很多事,但是也忽略了某些问题(比如这个溢出)
好像catch是可以多个的,但是我现在还不知道要怎么把溢出和非法这两个异常区别开,
Python里面也用过try,之后会更熟练一些把。
import java.util.Scanner;
import java.util.*;
public class Main {
public static void main(String[] args) {
int base, target;
String s;
Scanner reader = new Scanner(System.in);
while (reader.hasNext()) {
base = reader.nextInt();
target = reader.nextInt();
s = reader.next();
// 尝试使用try-catch来处理异常
//FFFFFFFFFF base 16 = 1111111111111111111111111111111111111111 base 2
//FFFFFFFFFF is an illegal base 16 number
//上面这组测试数据过不去,因为太长了
try {
String sum = Integer.toString(Integer.valueOf(s, base), target);
System.out.println(s + " base " + base + " = " + sum + " base " + target);
}
catch(Exception e) {
System.out.println(s+" is an illegal base "+base+" number");
continue;
}
}
}
}