写一个把字符串转成整型的方法,出错时返回默认值

zhangshengyuan1545 2012-06-18 07:49:23
定义名为: TestException1.java的类
2) 写一个把字符串转成整型的方法,出错时返回默认值
public static int stringToInt(String str, int defaultValue){ //… };
...全文
934 4 打赏 收藏 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
woaini245693140 2012-06-18
  • 打赏
  • 举报
回复
public static int stringToInt(String str) {
String reg = "\\d{1,}"; //这是正则表达示 str 必须是一位或多位数字组成,
//否则返回-1
if (str.matches(reg)) {
return Integer.parseInt(str);
} else {
return -1;
}
}
楼上写的也可以,
两种办法,楼主自己选吧!
sdojqy1122 2012-06-18
  • 打赏
  • 举报
回复
这个很简单啊
public class TestException1 {
public static void main(String args[]){
String str="222";
TestException1.stringToInt(str, 0);

}
public static int stringToInt(String str, int defaultValue){
int result = 0;
try{
result = Integer.parseInt(str);
}catch(NumberFormatException e){
//e.printStackTrace();
System.out.println("参数不能转化为Integer型,以默认值输出");
result = defaultValue;
}
return result;

}
}
古市轩 2012-06-18
  • 打赏
  • 举报
回复
int value = defaultValue;
try
{
value = Integer.parse(str);
}
catch(Exception e)
{
e.printStackTrace();
}

return value;
MiceRice 2012-06-18
  • 打赏
  • 举报
回复 1
楼主是在狂问老师布置的作业?


public static int stringToInt(String str, int defaultValue){
try {
return Integer.parseInt(str);
} catch (Exception ex) {
return defaultValue;
}
}

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧