0

This an example input: 1002372 I need to get an output like this: 0012237 I am required to use loops, and boolean algebra. I've converted the int into a String and I tried this for a start:

x = String.valueOf(a);
y = String.valueOf(b);

for(int z = 0; z < x.length(); z++)
{
    if(x.charAt(z) == '0')
    {
        System.out.println(x.charAt(z));
    }
    if(x.charAt(z) == '1')
    {
        System.out.println(x.charAt(z));
    }
}

Instead of running through and finding all the zeros first, the program just prints the numbers in order.

How do I check and print all of one integer at a time?

Anil
  • 655
  • 1
  • 11
  • 25

2 Answers2

2

You are on the right path, to complete your logic, you'll need an additional loop to iterate digits 0 to 9 inclusive and compare the string at index z against it as follow.

Solution #1: Using string

String numberStr = String.valueOf(1002372);

for (int digit = '0'; digit <= '9'; digit++) {
    for (int index = 0; index < numberStr.length(); index++) {
        if (numberStr.charAt(index) == ((char) digit)) {
            System.out.print(numberStr.charAt(index));
        }
    }
}

Solution #2: Using integer

int number = 1002372;
int tempNumber, tempDigit;

for (int digit = 0; digit <= 9; digit++) {
    tempNumber = number;
    while (tempNumber > 0) {
        tempDigit = tempNumber % 10;
        tempNumber = tempNumber / 10;

        if (tempDigit == digit) {
            System.out.print(tempDigit);
        }
    }
}
peclevens
  • 21
  • 1
  • 5
0

You can also use (if don't want to use loop),

public String sortNumber(int inputNumber) 
    { 
        // convert to string
         String s_number = inputNumber + "";

        // convert string to char array 
         char tempArray[] = s_number.toCharArray(); 

        // sort tempArray 
         Arrays.sort(tempArray); 

        // return new sorted string 
         return new String(tempArray); 
    }
Md. Shohag Mia
  • 322
  • 3
  • 13