2015-09-22 12 views
0

我試過了一個程序,但它顯示了第一個數字。我需要使用while循環的中間數字程序。 我用以下各項如何打印數字的中間數字?

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; 

      } 
     } 
    } 

} 

但它一直在給予同樣的輸出 -

The mid digit of 345 is 3 

請幫幫我!

+1

你有沒有做到這一點使用這個相同的邏輯?或者任何邏輯會做? –

+0

'5678'的中間數字應該是多少?在編碼之前確保你有你的要求。 – Andreas

回答

3

如果使用不同的邏輯不介意,你可以試試這個..

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."); 
    } 
0

您計算m的位置中間的數字,但你不使用它。

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

如果你想堅持爲int然後用這個

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); 
    }