java.lang.Byte.parseByte()方法範例


java.lang.Byte.parseByte(String s) 解析字串引數作為有符號十進位制位元組。字串中的字元必須是十進位制數位,除非第一個字元為ASCII字元減號' - '(' u002D')來表示一個負值或ASCII碼加號'+'(' u002B')以表示正值。

由此產生的位元組值返回,就好像在引數和基數10作為引數傳遞給parseByte(java.lang.String, int) 方法。

宣告

以下是java.lang.Byte.parseByte()方法的宣告

public static byte parseByte(String s)throws NumberFormatException

引數

  • s - 要分析包含位元組表示一個字串

返回值

此方法將返回由十進位制引數表示的位元組值。

異常

  • NumberFormatException - 如果字串中不包含一個可分析的位元組。

例子

下面的例子顯示了lang.Byte.parseByte()方法的使用。

package com.yiibai;

import java.lang.*;

public class ByteDemo {

   public static void main(String[] args) {

      // create 2 byte primitives bt1, bt2
      byte bt1, bt2;

      // create and assign values to String's s1, s2
      String s1 = "+123";
      String s2 = "-123";

      /**
       *  static method is called using class name. 
       *  assign parseByte result on s1, s2 to bt1, bt2
       */
      bt1 = Byte.parseByte(s1);
      bt2 = Byte.parseByte(s2);

      String str1 = "Parse byte value of " + s1 + " is " + bt1;
      String str2 = "Parse byte value of " + s2 + " is " + bt2;

      // print bt1, bt2 values
      System.out.println( str1 );
      System.out.println( str2 );
   }
}

讓我們來編譯和執行上面的程式,這將產生以下結果:

Parse byte value of +123 is 123
Parse byte value of -123 is -123