当前页面: 开发资料首页 → J2SE 专题 → 请问一个将字符串转换为long的程序
请问一个将字符串转换为long的程序
摘要: 请问一个将字符串转换为long的程序
一道笔试题,要求将字符串转换为long型,不知道该怎么做,请大家帮帮忙
long num=Long.parseLong(str);
只要你的字符串是数字类型的,如"123"等都可以利用
Long.parseLong(str)来处理
但是,如果字符串中有字母出现,就不行了
System.out.println(Long.parseLong("a123"));
会报如下错误:
Exception in thread "main" java.lang.NumberFormatException: For input string: "a123"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Long.parseLong(Long.java:403)
at java.lang.Long.parseLong(Long.java:461)
try
{
long num=Long.parseLong(str);
}
catch(NumberFormatException e)
{
}
Long.parseLong(str)
注意抛出异常
long num = 0;
try
{
num = new Long(str).longValue;
}
catch(NumberFormatException e)
{
num = 0;
}
public class test {
public static void main(String[] args) {
String str= "100000";
Long lnum = new Long(str);
lnum.longValue();
System.out.println("值是:"+lnum);
}
}
String temp="1000";
int count=0;
for(int i=0;i
{
Pattern p=Pattern.compile("[//d]");
Matcher m=p.matcher(temp.charAt(i)+"");
if(m.find())
{ count++; }
}
if(count==temp.length())
{
System.out.println(Long.parseLong(temp));
}
else
{
System.out.println("该字符串中包含非字母的字符,不能转换为long型");
}
try
{
long num=Long.parseLong(str);
}
catch(NumberFormatException e)
{
}
--------------------------------------------
顶一下...
估计别人不是考你使用API,而是自己写一个:
public static void main(String[] args) {
char[] s = "a12345".toCharArray();
System.out.println("long is "+atol(s));
}
static long atol(char[] num_str)
{
long result = 0;
int quotient = 0;
for (int i = num_str.length-1; i != 0; i--)
{
char c = num_str[i];
if (c < '0' || c > '9') continue;
long pow = 1;
for (int tmp = 1; tmp <= quotient; tmp++)
pow*=10;
result += (c-'0')*pow;
++quotient;
}
return result;
}
sorry,change 'i !=0 ' to 'i != -1' .