How to concatenate seperate digits from a loop into one single integer

okay so I have an assignment that says i have a string of numbers for example “1234 4014 5555 7654” say which is essentially a credit card number. They are asking me to convert the string of digits into single integers then concatenate them into 4 lots of 4 digit integers so the string “1234 4014 555 7654” for example will have 4 blocks block 1 would be 1234 which is converted into 1, 2, 3, 4 which is then concatenated into 1234 as an integer i have to do this for all the blocks… ๐Ÿ™

So far.. i made a for loop as shown below :

public static int toInt(String digitString)
    int answer = 0;
    int num = 0;
    for (int j = 0; j < digitString.length(); j++){
        num = (int) digitString.charAt(j) - '0';

    return answer


and i can successfully convert the string into seperate digits but i have no idea how i can concatenate those digits into 4, 4 digit integers

any help would be much appreciated ๐Ÿ™‚


I’m not going to do your assignment for you, but I’ll tell you this hint: All you need to know to understand and solve this problem is that Integer.parseInt(s) for some String s returns s as an integer, and that s.substring(n, n+1) returns the (n+1)st character of a String.

For example

String s = "1234";
s = s.substring(0, 1); //s = "1"
int val = Integer.parseInt(s); //val = 1

And that’s it. Now it’s just a matter of looping over your String and doing whatever you want with them. I suppose it might be helpful to know that you can assign an integer to a string with:

String temp = val + "";
String temp = String.valueOf(val);

Leave a Reply

Your email address will not be published. Required fields are marked *