• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

do while loop in Java code help needed !

ninadchaudhari

What's up !
Hi,
Source code
Code:
public static void main(String args[])
    {
        
        System.out.println("Enter the Number");
        
        int num = Integer.parseInt(args[0]);
        
        int cnt=1;
        double i;
        
        do{
            i = (num/(Math.pow(10,cnt)));
            
            cnt++;
            System.out.println(cnt+" "+i);
        }while(i == 0);
}

I am totally confused why the loop is just executed once !


It is compiled with no errors
but during run time, the loop is excuted once though because of the println function, i can notice the value of i to be non zero !!
Just passed a 3 digit no. as argument ...
please can any one explain ???
 
It always runs through the loop at least once since its a do, while and not a for statement. While the variable "i" is equal to 0, it will return to the beginning of the loop to execute the code again. Since "i" is not equal to 0, the loops ends, thats why it only goes through once.

What are you trying to do with the loop, and why are you using "args" from the main function?

Lets go through each line of code:
Say you enter 123 as your number.
"num"=123
"cnt"=1
"i"=0.0

do{
i=(123/(10^1)) = i=12.3
cnt++; cnt=2
OUTPUT: "2 12.3"
}while(i==0) is false because i=12.3. A while condition returning false ends the loop.
 
Hey ! great thanks ... :)

I do not know what made me think while loop in a for loop manner ;) thanks again for clearing the problem :D .

ANyways,
I was just writing a trial code !
I mean nothing from any big project or something ...
Just practicing loops (in java) and go stuck here :o

I was just thinking on various ways to reverse the entered number 3-4 digits
like 123 -> 321 !
it is easy for 2 digits but i think it becomes more complicated for numbers with variable length hence it was my attempt to use Do while loop for calculating exact number of digits in the number so i can proceed with other functions :rolleyes:

btw ,
now i solved by converting Double i into int then converting == to != ...

i think i must clear the logic with loops :fisheye:
 
If you want to get the number of digits, you can convert the number into a string then use .length as shown:

int num = 12345;
String s = Integer.toString(num);
int length = s.length()

Or use a loop and division:

int num=12345;
int length = 0;
while (num>0)
{
length++;
num/=10;
}


There are various ways of reversing the digits, from math+loops, to converting it to a string or an array of chars.
 
Back
Top Bottom