Good day. There is an array of numbers.

Tell me how to properly make an array, for the subsequent output in System.out.println numbers in one line without spaces and separators. And I don’t know how to make the array consist of a number of elements equal to the number of characters to be output (I have 20 in the code, but this is not correct).

  • and what does this code do at all? Maybe write a task, this code can certainly be fixed, but it seems to me to rewrite it better. Do you think this is the most normal way to convert decimal to binary? - pavel
  • @pavel, the task was to translate, without using Integer.toBinaryString (), that’s what I did with my own methods)

3 answers 3

I would do something like that.

 class toBin{ ArrayList<Integer> arr; toBin(int number) { arr = new ArrayList<>(); for ( ; number > 0; number/=2) arr.add(number & 1); for (int x : arr) System.out.print(x); System.out.println(""); } } 

    There are several ways:

    1. Guava Joiners: http://google.imtqy.com/guava/releases/snapshot/api/docs/com/google/common/base/Joiner.html

    2. or so in java8

       Optional<String> str = Arrays.stream(a) .mapToObj(String::valueOf) .reduce((e, t) -> t.concat(e)) .map(e -> new StringBuilder(e).reverse().toString()); if (str.isPresent()) System.out.println(str.get()); 

      This is how you can make the output of an array of numbers as a string for System.out.println() without spaces or separators:

        public class PrintIntArray{ public static String arrayIntToString(int[] arr){ StringBuilder sb = new StringBuilder(); for (int element: arr) sb.append(element); return String.valueOf(sb); } public static void main(String[] args) { int[] i = {1,2,3}; System.out.println(arrayIntToString(i)); } } /* Output: 123 *///:~