一道笔试题,要求将字符串转换为long型,不知道该怎么做,请大家帮帮忙

解决方案 »

  1.   

    只要你的字符串是数字类型的,如"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)
      

  2.   

    try
    {
        long num=Long.parseLong(str);
    }
    catch(NumberFormatException e)
    {
        
    }
      

  3.   

    Long.parseLong(str)
    注意抛出异常
      

  4.   

    long num = 0;
    try
    {
       num = new Long(str).longValue;
    }
    catch(NumberFormatException e)
    {
       num = 0;
    }
      

  5.   


    public class test {

    public static void main(String[] args) {

    String str= "100000";
    Long lnum = new Long(str);
    lnum.longValue();
    System.out.println("值是:"+lnum);

    }
    }
      

  6.   

    String temp="1000";
       int count=0;
       for(int i=0;i<temp.length();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型");
       }
      

  7.   

    try
    {
        long num=Long.parseLong(str);
    }
    catch(NumberFormatException e)
    {
        
    }
    --------------------------------------------
    顶一下...
      

  8.   

    估计别人不是考你使用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;
    }
      

  9.   

    sorry,change 'i !=0 ' to 'i != -1' .