user1213994
user1213994

Reputation: 13

Java program to separate an integer

I've written the following code in Java to separate an integer. Example: 12345 to 1 2 3 4 5

Here is the code:

public class Modulus {

public static void main(String[] args) {
    int number=Integer.parseInt(args[0]);
    String counter= Integer.toString(number);
    int count=(int)(counter.length()-1);

Upvotes: 1

Views: 501

Answers (5)

raveturned
raveturned

Reputation: 2677

Coming out of the first while loop you'll have count>=0 evaluating to false - count will be negative.

Going into the second while loop, you're trying to evaluate track[count]. If count is negative, this will throw the ArrayIndexOutOfBoundsException.

Edit: as pointed out by hvgotcodes - the exception you're seeing is actually being thrown earlier in the code.

int [] track = new int[count];   // int of length count - indexed 0 to count-1

    while (num > 0 && count>=0) {
        track[count]=(num % 10); // get value indexed count - out of bounds!

Once this is resolved, you may run into the issue I've spotted. ;)

Upvotes: 0

hvgotcodes
hvgotcodes

Reputation: 120268

You want counter.length() not counter.length()-1, when you create the array. The indexes of the array goes to n-1, not the length of the string (which is n).

When you loop thru the array, you want to start at count-1, and go down from there.

If the number is 12345, then your array needs to be of size 5, to hold the 5 digits, and the indexes go from 0-4. Accordingly, you want to create the array with count, and start printing at count-1.

That should address your index out of bounds issue, but you have other issues too.

Note your loop will stop as soon as it finds a zero, even if its in the middle of the digits. So if you have 3405, your app will print 5 and then stop.

Also, the comments to your question hint at overall simpler approaches, although what you are doing is fine for learning.

Upvotes: 3

sgowd
sgowd

Reputation: 2262

Try this:

 public class Modulus {

    public static void main(String[] args) {
        String numString = "12345";
        int num = Integer.parseInt(numString);
        char[] numCharArray = numString.toCharArray();
        for(int i=0;i<numCharArray.length;i++){
            System.out.print(numCharArray[i]+i != numCharArray.length-1 ? " " : "");
        }
    }
}

Upvotes: 0

ParPar
ParPar

Reputation: 7569

Try this:

counter.replaceAll(".(?=.)", "$0 ") 

It will replace each character with the character+ a sapce.

Upvotes: 0

Masa
Masa

Reputation: 311

Array index starts from zero. So if you do int count=(int)(counter.length()-1); if suppose your count is 3, you can have indexes 0, 1, 2 When you write track[count]=(num % 10), you trying track[3] and thus you are getting error.

Upvotes: 0

Related Questions