Chester Paul
Chester Paul

Reputation: 31

How to print the middle digit of a number if so?

I tried a program but it shows the first digit. I want a mid digit program by using while loop. I used the following-

public class MID {

    public static void Indra(int n) {
        int a = 0, c = 0, m = 0, r = 0;
        a = n;
        while (n != 0) {
            c++;
            n = n / 10;
        }
        n = a;
        if (c % 2 == 0) {
            System.out.println("No mid digit exsist!!");
        } else {
            m = (c + 1) / 2;
            c = 0;
            while (n != 0) {
                c++;
                r = n % 10;
                if (c == r) {
                    System.out.println(r);
                }
                n = n / 10;

            }
        }
    }

}

But it keeps on giving the same output-

The mid digit of 345 is 3

Please,help me!

Upvotes: 0

Views: 11046

Answers (3)

Lawgrin Foul
Lawgrin Foul

Reputation: 308

If you want to stick to int then use this

    if (c == 1 || c % 2 == 0) {
        System.out.println("No mid digit exsist!!");
    }
    else
    {
        m = c/2;
        int lower = (int)(n % Math.pow(10, m));
        int upper = n-((int)(n % Math.pow(10, m+1)));

        r = n-(upper+lower);
        while (r >= 10)
        {
            r = r/10;
        }

        System.out.println(r);
    } 

Upvotes: 0

Jos
Jos

Reputation: 2013

If you dont mind using a different logic, you can try this..

    int x = 354;
    String num = Integer.toString(x);
    if(num.length() % 2 != 0){
        System.out.println("The mid digit of " + x + " is " +  num.charAt(num.length()/2));
    }else {
        System.out.println("No middle number.");
    }

Upvotes: 3

Peter Lawrey
Peter Lawrey

Reputation: 533492

You calculate m for the position middle digit, but you don't use it.

m = (c + 1) / 2;
for (int i = 0; i < m; i++)
    n /= 10;
System.out.println(n % 10);

Upvotes: 0

Related Questions