jAVA高手请进,帮忙用java编写两个关于异常的题。要能用myeclipse运行出来的。感谢啊
1.派生一个字符串类,使字符串能限制长度。当字符串长度大于指定长度时,抛出一个StringTooLargeException异常。2.编写程序包含自定义异常,用于数值运算...
1.派生一个字符串类,使字符串能限制长度。当字符串长度大于指定长度时,抛出一个StringTooLargeException异常。2. 编写程序包含自定义异常,用于数值运算时在输入的字符中检测非数字字符,并编写抛出异常时的提示“使用非法字符”,测试异常。
紧急紧急啊!!!!请大家帮帮忙! 这是两道题哈 展开
紧急紧急啊!!!!请大家帮帮忙! 这是两道题哈 展开
2个回答
展开全部
so easy 输入部分自己写啊
public class StringTest {
private static final Exception Exception = null;
private static int len=10;
public static void main(String[] args) throws Exception {
testString("asdsadd123123");
parseNum("12a");
}
public static String testString(String str) throws StringTooLargeException{
if(str.length()>len){
//异常的抛出
throw new StringTooLargeException("StringTooLargeException");
}
return str;
}
public static int parseNum(String str)
throws IllegalNumberException{ //异常的声明
char[] chars = str.toCharArray();
int sum = 0;
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if(c > '9' || c<'0'){
//异常的抛出
throw new IllegalNumberException("使用非法字符");
}
sum = sum*10 + (c-'0');
}
return sum;
}
}
class IllegalNumberException extends Exception {
public IllegalNumberException(String string) {
super(string);
}
}
class StringTooLargeException extends Exception {
public StringTooLargeException(String str) {
super(str);
}
}
public class StringTest {
private static final Exception Exception = null;
private static int len=10;
public static void main(String[] args) throws Exception {
testString("asdsadd123123");
parseNum("12a");
}
public static String testString(String str) throws StringTooLargeException{
if(str.length()>len){
//异常的抛出
throw new StringTooLargeException("StringTooLargeException");
}
return str;
}
public static int parseNum(String str)
throws IllegalNumberException{ //异常的声明
char[] chars = str.toCharArray();
int sum = 0;
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if(c > '9' || c<'0'){
//异常的抛出
throw new IllegalNumberException("使用非法字符");
}
sum = sum*10 + (c-'0');
}
return sum;
}
}
class IllegalNumberException extends Exception {
public IllegalNumberException(String string) {
super(string);
}
}
class StringTooLargeException extends Exception {
public StringTooLargeException(String str) {
super(str);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询