Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

1. ## Stuck on this problem please help

hello, Im new to Java and am taking a class. Ive been working on this problem for over 4 hours now and am stuck. this is the problem:

If you divide 1 by 2, you get 0.5. If you divide it again by 2, you get 0.25. Write a
program using dowhile loop to calculate and output the number of times you have to
divide 1 by 2 to get a value less than one ten-thousands (0.0001)..

Ive tried several ways but nothing is working for me. this is my current code:

public class Divide {
public static void main(String[] args) {
double n =1;
double Final=NumR(n);
System.out.println(Final);
}
public static double NumR(double z){
double x=2;
double i =z;
double total;

do{
i =i/x;

i++;

return i;}
while(total >=.0001);

}}

it doesnt work, Im stuck. How do i return the value of the division so that i can divide it again?

--- Update ---

i think i solved it please check:
public class Divide {
public static void main(String[] args) {

double x = 1;
double count = 0;
double tempNum = x / 2;

while (tempNum >= .0001){
tempNum = tempNum / 2;
count++;

}
System.out.println("The number " + x + " is divisible by two " + count + " times and equals " + tempNum);
}
}

one issue how do i turn it into a do while loop????

--- Update ---

public class Divide {
public static void main(String[] args) {

double x = 1;
double count = 0;
double tempNum = x ;

do {
tempNum = tempNum / 2;
count++;
}
while (tempNum >= .0001);

System.out.println("The number " + x + " is divisible by two " + count + " times and equals " + tempNum);
}
}

final code? does this look right?  Reply With Quote

3. ## Re: Stuck on this problem please help

Way to work through it. You are definitely getting the right answer as far as i can tell. I would recommend commenting the code (Teachers always like commented code. Shows you understand what you did). And change the variable "x" to something more descriptive like "initialValue". Simple variable names are evil. You're working in java and should use verbose variable names. It wont make your code run any slower so why not? Making this a practice will be more beneficial in the future.  Reply With Quote