不使用java內建函數,將String字串轉換為int類型

來源:互聯網
上載者:User

標籤:als   cas   bool   out   數字   col   def   不用   div   

package com.test;public class AtoiTest {  public static void main(String[] args) throws Exception {    String s = "-011134";    System.out.println("轉換前的字串:" + s);    System.out.println("atoi1轉換後的字串:" + atoi1(s));    System.out.println("atoi2轉換後的字串:" + atoi2(s));  }  /**   * 不用java內建函數,將String字串轉換為數字   * @param s   * @return   * @throws Exception    */  public static int atoi1(String s) throws Exception {    if (s == null || s.length() == 0) {      throw new Exception("要轉換的字串為空白,無法轉換!");    }    int retInt = 0;    int[] num = new int[s.length()];    for (int i = 0; i < s.length(); i++) {      char c = s.charAt(i);      switch (c) {      case ‘-‘:        num[i] = -1;        break;      case ‘0‘:        num[i] = 0;        break;      case ‘1‘:        num[i] = 1;        break;      case ‘2‘:        num[i] = 2;        break;      case ‘3‘:        num[i] = 3;        break;      case ‘4‘:        num[i] = 4;        break;      case ‘5‘:        num[i] = 5;        break;      case ‘6‘:        num[i] = 6;        break;      case ‘7‘:        num[i] = 7;        break;      case ‘8‘:        num[i] = 8;        break;      case ‘9‘:        num[i] = 9;        break;      default:        throw new Exception("要轉換的字串格式錯誤,無法轉換!");      }    }    for (int i = 0; i < num.length; i++) {      if (num[i] < 0 && i > 0) {        throw new Exception("要轉換的字串格式錯誤,無法轉換!");      }      if (num[i] < 0) {        continue;      }      retInt += Math.pow(10, num.length - i - 1) * num[i];    }    if (num[0] == -1) {//代表負數      retInt = -retInt;    }    return retInt;  }  /**   * 不用java內建函數,將String字串轉換為數字   * @param s   * @return   * @throws Exception   */  public static int atoi2(String s) throws Exception{    int retInt = 0;    if (s == null || s.length() == 0) {      throw new Exception("要轉換的字串為空白,無法轉換!");    }    boolean isNegative = false;    for (int i = 0; i < s.length(); i++) {      if (i==0) {        if(s.charAt(i)==‘-‘){          isNegative = true;          continue;        }      }else{        if(s.charAt(i)>‘9‘ || s.charAt(i)<‘0‘){          throw new Exception("要轉換的字串格式錯誤,無法轉換!");        }      }      retInt *=10;      retInt += s.charAt(i) - ‘0‘;    }    return isNegative ? -retInt : retInt;  }}

 

不使用java內建函數,將String字串轉換為int類型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.