Java - parseInt() 方法



描述

此方法用於獲取某個字串的原始資料型別。parseXxx() 是一個靜態方法,可以有一個或兩個引數。例如,parseInt() 用於 Integer 物件,parseDouble() 用於 Double 物件。

語法

以下是此方法的所有變體:

static int parseInt(String s)
static int parseInt(String s, int radix)

引數

以下是引數的詳細資訊:

  • s - 這是十進位制的字串表示形式。

  • radix - 這將用於將字串 s 轉換為整數。

返回值

  • parseInt(String s) - 返回一個整數(僅限十進位制)。

  • parseInt(Strings, int i) - 返回一個整數,給定十進位制、二進位制、八進位制或十六進位制(基數分別為 10、2、8 或 16)數字的字串表示形式作為輸入。

從字串獲取 int 示例

在此示例中,我們展示瞭如何使用 parseInt() 方法從字串獲取 int。首先,我們從字串中解析了一個 int,然後使用給定的基數對其進行了解析。此後列印兩者。

public class Test { 
   public static void main(String args[]) {
      int x =Integer.parseInt("9");
      int b = Integer.parseInt("444",16);

      System.out.println(x);
      System.out.println(b);
   }
}

這將產生以下結果:

輸出

9
1092

從字串獲取 double 示例

在此示例中,我們展示瞭如何使用 parseDouble() 方法從字串獲取 double。我們從字串中解析了一個 double 並列印它。

public class Test { 
   public static void main(String args[]) {
      double x = Double.parseDouble("9.0");

      System.out.println(x);
   }
}

這將產生以下結果:

輸出

9.0

從字串獲取 long 示例

在此示例中,我們展示瞭如何使用 parseLong() 方法從字串獲取 long。我們從字串中解析了一個 long 並列印它。

public class Test { 
   public static void main(String args[]) {
      long x = Long.parseLong("9");

      System.out.println(x);
   }
}

這將產生以下結果:

輸出

9
java_numbers.htm
廣告