Output issue while printing array of char

When I print the the element of the array of char the index in [5] & [6] are not correct in the output.

package id_code;
import java.util.Scanner;

public class Main {
 
    public static void main(String[] args) {
        // creating input
        Scanner input = new Scanner(System.in);
        
        System.out.println("Enter your Id: ");
        long id = input.nextLong();
        
        // convert id from (int) to (String)
        String str_id = String.valueOf(id);
        
        // convert id (String) to array of (char[])
        char[] id_holder = str_id.toCharArray();
        
        // print elemnt of array 
        System.out.print(id_holder[5] + id_holder[6] + " - " + id_holder[3] + id_holder[4] + " - " + id_holder[1] + id_holder[2] + "\n");
        
       
        // Index ->  0 1 2 3 4 5 6 7 8 9 10
        // number -> 1 1 2 2 3 3 4     

    }
    
}

Output:

Enter your Id: 

1302579

112 - 25 - 30

The correct output should be:

79 - 25 - 30

Any reasons why is that happening?

>Solution :

The problem the first expression being printed in this line

System.out.print(id_holder[5] + id_holder[6] + " - " + id_holder[3] + id_holder[4] + " - " + id_holder[1] + id_holder[2] + "\n");

Is id_holder[5] + id_holder[6] which is arithmetic: Java casts each char to int (their ascii value) and adds them to total 112.

The next term added is a string, so Java concatenates 112 and " – " to give another string, and from then on the string is built up.

One simple way to fix this is to start with a string (a blank string):

System.out.print("" + id_holder[5] + id_holder[6] + " - " + id_holder[3] + id_holder[4] + " - " + id_holder[1] + id_holder[2] + "\n");

By doing this, Java will concatenate each term (one at a time) as a string.


BTW another way to achieve the result, using only 1 line of code, is using regex:

System.out.println(String.valueOf(id).replaceAll(".(..)(..)(..)", "$3 - $2 - $1"));

Leave a Reply