0

Before that sorry for my bad english because it's not my first language. Excuse me, i'm trying to convert array byte to string in error handling try catch java. And if user input integers, the result will be +2. I've tried but always error, i hope someone can help me.

Here's my code:

 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));
        }
    }
Origami
  • 47
  • 2
  • 9
  • Does this answer your question? [How to convert byte array to string and vice versa?](https://stackoverflow.com/questions/1536054/how-to-convert-byte-array-to-string-and-vice-versa) – Michał Krzywański Jun 02 '20 at 13:12

3 Answers3

2

To convert a byte[] to String use s=new String(bytes,"UTF-8") or whatever encoding has been used.

However I assume that you misunderstood how the console works because you asked for a conversion to string but you need integer. We normally use the Scanner class to read interactive input and convert it.

Take a look at this tutorial, which explains how to use the scanner class: https://www.w3schools.com/java/java_user_input.asp

Stefan
  • 1,789
  • 1
  • 11
  • 16
0

Just like that:

byte[] bytes = new byte[5];
String stringFromByteArray = new String(bytes);
-1

Here's the solution:

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
}

EXAMPLE: if the 5 bytes are {1,2,3,4,5}, the string is "12345"

FoxWare
  • 14
  • 2
  • 1
    I don't think this is an appropriate solution as `Byte.toString` which calls `Integer.toString` under the hood is only good for converting numeric values, but the original question did not specify a `byte[]` of only numbers, but a `byte[]` in general. `new String(byte[], charset)` is much more appropriate. Your solution also leaves limited control for post processing or validation such as using a locale aware number formats for localized inputs. – Seth Falco Jun 02 '20 at 13:22