java通用方法共享

歡迎各位將你們的一些公共方法共享:
    // 得到隨機的n個字符

    public static String randomStr(int n) {
  String str1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
  String str2 = "";
  int len = str1.length() - 1;
  double r;
  for (int i = 0; i < n; i++) {
      r = (Math.random()) * len;
      str2 = str2 + str1.charAt((int) r);
  }
  return str2;
    }
    // 將10進制數num10轉換爲2進制數
    public static String to2b(long num10) {
  long temp = num10;
  String result1 = "";
  while (temp > 0) {
      result1 = String.valueOf(temp % 2) + result1;
      temp = temp / 2;
  }
  return result1;
    }
    // 將2進制數num2轉換爲10進制數
    public String to10b(String num2) {
  int temp = 0;
  for (int i = 0; i < num2.length(); i++) {
      temp = (temp * 2)
        + Integer.parseInt(String.valueOf(num2.charAt(i)));
  }
  return String.valueOf(temp);
    }
    // 返回a/b的百分數
    public String getDivide(int a, int b) {
  String res = "0";
  if (b != 0 && a != 0) {
      res = (a * 100 / b) + "%";
  }
  return res;
    }
    // 判斷strEmail是否爲Email格式
    public static boolean isEmail(String strEmail) {
  String temp = new String(strEmail);
  boolean re = false;
  String ss = "@";
  int m = 0;
  int n = 0;
  for (int i = 0; i < temp.length(); i++) {
      if (temp.charAt(i) == ss.charAt(0)) {
    m = m + 1;
    n = i;
      }
  }

  String kk = ".";
  int k = 0;
  for (int i = 0; i < temp.length(); i++) {
      if (temp.charAt(i) == kk.charAt(0)) {
    k = i;
      }
  }

  if ((m == 1) && n > 0 && (n < temp.length() - 1) && k > n + 1) {
      re = true;
  }
  return re;
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章