[英]How to convert array byte to string in java
在那之前,我很抱歉我的英語不好,因為它不是我的第一語言。 對不起,我正在嘗試在錯誤處理中將數組字節轉換為字符串嘗試捕獲 java。 如果用戶輸入整數,結果將為+2。 我試過但總是出錯,我希望有人能幫助我。
這是我的代碼:
package exception;
public class TugasTiga {
public static void main (String [] args) {
byte[] b = new byte[5];
System.out.println("Input bilangan bulat: ");
try { System.in.read(b);
} catch (java.io.IOException e);
int N = Integer.valueOf(b).intValue();
System.out.println("Hasil: " + (N+2));
}
}
要將 byte[] 轉換為 String,請使用s=new String(bytes,"UTF-8")
或已使用的任何編碼。
但是我假設您誤解了控制台的工作原理,因為您要求轉換為字符串,但您需要 integer。 我們通常使用Scanner
class 來讀取交互式輸入並進行轉換。
看看這個教程,它解釋了如何使用掃描儀 class: https://www.w3schools.com/java/java_user_input.asp
就像這樣:
byte[] bytes = new byte[5];
String stringFromByteArray = new String(bytes);
這是解決方案:
byte[] bytes = new byte[5]; //create the list
String finalS = ""; //create the string
for(byte element : bytes) { //for all elements in the list
finalS += Byte.toString(element); //add to the string "finalS" the byte converted to string
}
示例:如果 5 個字節為{1,2,3,4,5}
,則字符串為"12345"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.