thyn_bandwagon
thyn_bandwagon

Reputation: 3

Won't print x in for loop

I'm trying to make it so that code prints out x (squaring x each time), until it reaches number that divides the current time (in milliseconds) into a single digit. It doesn't have any errors, but it also has no output. How can I make it print out x?

public class Experiment {

    public static void main(String[] args){

         long start = System.currentTimeMillis();

         for(long x = 2; System.currentTimeMillis() / x <= 9; x=x*2){
             System.out.println(x);
         }
    }
}

Upvotes: 0

Views: 154

Answers (5)

Winter
Winter

Reputation: 122

Your loop is ending before the first iteration.

for(long x = 2; System.currentTimeMillis() / x <= 9; x=x*2)

The conditional statement in your loop has to be met originally in order for the loop to iterate.

Since the current time / x is not smaller than 9 on the first iteration the loop exits immediately.

I believe if you change

System.currentTimeMillis() / x <= 9

To

System.currentTimeMillis() / x > 9

This should work

Upvotes: 0

Suparna
Suparna

Reputation: 1182

A simple debugger run would reveal that you are trying to compare a value: 729466267577 against 9 and expecting it to be less than 9.

I think there is no need to tell you how to solve this one. But what SO will tell you is start using some kind of debugger

Upvotes: 0

RaminS
RaminS

Reputation: 2239

Your error is in writing System.currentTimeMillis() / x <= 9 instead of System.currentTimeMillis() / x > 9.

Your loop is not running even once, since it cannot satisfy System.currentTimeMillis() / x <= 9.

Side note: Keep in mind that System.currentTimeMillis() / x is not always an integer. If by "single digit" you mean "less than 10" (e.g. 9.563), you should instead write System.currentTimeMillis() / x >= 10. However, I doubt that division between two long would produce a decimal number.

Upvotes: 6

apheniti
apheniti

Reputation: 66

The loop is not running! Try with System.currentTimeMillis() / x >= 9, it should work. I've tried it on Eclipse and it prints:

2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
32768
65536
131072
262144
524288
1048576
2097152
4194304
8388608
16777216
33554432
67108864
134217728
268435456
536870912
1073741824
2147483648
4294967296
8589934592
17179869184
34359738368
68719476736
137438953472

Upvotes: 0

Sci Prog
Sci Prog

Reputation: 2691

From your description

public class Experiment {
  public static void main(String[] args){
     final long start = System.currentTimeMillis() / 10;
     for(long x = 2; x <= start; x*=2){
         System.out.println(x);
     }
  }
}

I wasn't sure about "number that divides the current time (in milliseconds) into a single digit", but you should be able to continue.

Upvotes: 0

Related Questions