After converting an array of numbers of type int into a string using the Arrays.toString () method; The indexOf () method has stopped working. That is, when such code is executed, -1 is always displayed on the screen. How to fix it?

int n = 10; int[] mass = new int[n]; int a = 0, b = 10; //fill in the mass with random numbers for(int i=0; i < n; i ++){ mass[i] = a + (int)(Math.random()*b); } String str = Arrays.toString(mass); System.out.println(str.indexOf(mass[0])); 

    2 answers 2

    We read the documentation .

    If you pass an int to indexOf (), the function considers it as a character code.

    You need to convert an int to a string and pass it to the method.

    Call this:

     System.out.println(str.indexOf(Integer.toString(mass[0]))); 

    Or so:

     System.out.println(str.indexOf(String.valueOf(mass[0]))); 

    Or so:

     System.out.println(str.indexOf(mass[0] + "")); 

      Give the search argument to the line:

       System.out.println(str.indexOf(mass[0] + "")); // 1 

      Pay attention to the feature of the selected array serialization method:

       String str = Arrays.toString(mass); System.out.println(str); // "[3, 5, 8, 3, 0, 5, 3, 4, 0, 3]" 

      If this is not what you need, try another method:

       StringBuilder sb = new StringBuilder(mass.length); for (int i : mass) { sb.append(i); } String s = sb.toString(); System.out.println(s); // "3583053403" 
      • OK, but why then if after the string String str = Arrays.toString (mass); add mass sorting of the mass array and then call the str.indexOf (mass [0] + "") method, then the number that is greater than 10 is displayed on the screen, although there were 10 characters in the array? - Bohdan
      • Ah, if only) I’ll add a little bit in response - vp_arth
      • Can I somehow get a string like "3583053403" without a loop? - Bohdan
      • to remove through replace commas, spaces and square brackets? =) - vp_arth
      • There was also StringUtils.join in my StringUtils.join - vp_arth