Java字串轉位元組程式
假設你有一個名為"str"的字串。現在,你的任務是編寫一個Java程式將給定的字串轉換為位元組。
字串是Java中一個類,它在雙引號記憶體儲字元序列,而位元組是包裝類,屬於java.lang包,它包裝了位元組資料型別的數值。
示例場景
Input: String str = "65"; Output: res = 65
使用Byte.valueOf()方法
Java Byte類的valueOf()方法用於將給定的字串轉換為其對應的Byte物件。它接受單個數字字串作為引數值,並將其作為Byte物件返回。
示例
下面的Java程式演示瞭如何將給定的字串轉換為位元組。
public class Demo {
public static void main(String[] args) {
String str = "65";
System.out.println("Given String is: " + str);
// checking type before converting
System.out.println("Type before converting: " + ((Object)str).getClass().getSimpleName());
// converting to byte using Byte.valueOf()
byte res = Byte.valueOf(str);
System.out.println("String after converting to Byte: " + res);
// checking type after converting
System.out.println("Type after converting: " + ((Object)res).getClass().getSimpleName());
}
}
執行此程式碼將生成以下結果:
Given String is: 65 Type before converting: String String after converting to Byte: 65 Type after converting: Byte
使用Byte.parseByte()方法
Java Byte類的parseByte()方法將指定的字串引數解析為帶符號的十進位制位元組。
示例
在這個Java程式中,我們傳遞一個帶符號的數字字串,並使用parseByte()方法將其轉換為位元組。
public class Demo {
public static void main(String[] args) {
String str = "-127";
System.out.println("Given String is: " + str);
// checking type before converting
System.out.println("Type before converting: " + ((Object)str).getClass().getSimpleName());
// converting to byte using Byte.parseByte()
byte res = Byte.parseByte(str);
System.out.println("String after converting to Byte: " + res);
// checking type after converting
System.out.println("Type after converting: " + ((Object)res).getClass().getSimpleName());
}
}
上述程式碼的輸出為:
Given String is: -127 Type before converting: String String after converting to Byte: -127 Type after converting: Byte
處理字串轉位元組時的錯誤
Byte.parseByte()和Byte.valueOf()方法都期望一個字串,該字串表示位元組資料類型範圍內的值,即-128到127之間的數字。因此,你需要傳遞其範圍內的數字字串,否則可能會遇到NumberFormatException異常。
示例
現在,讓我們看看實際演示:
public class Demo {
public static void main(String[] args) {
// string value is greater than Byte range
String str = "130";
System.out.println("Given String is: " + str);
// converting to byte
byte res = Byte.valueOf(str);
System.out.println("String after converting toByte: " + res);
}
}
執行此程式碼時,將顯示以下錯誤訊息:
Given String is: 130 Exception in thread "main" java.lang.NumberFormatException: Value out of range. Value:"130" Radix:10 at java.base/java.lang.Byte.parseByte(Byte.java:195) at java.base/java.lang.Byte.valueOf(Byte.java:249) at java.base/java.lang.Byte.valueOf(Byte.java:275) at Demo.main(Demo.java:7)
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP