Gyandeep Pattnayak
Gyandeep Pattnayak

Reputation: 31

Need to read the last value from an output of n numbers

I have a part of a program which looks like this.

for(int i=0;i<50;i++)
{
   Random t = new Random();

// random integers in [0, 100]
  System.out.println(t.nextInt(100));
}

I need to redirect just the last value to a text file. Any way I can print just the last value on the console? The very last value and nothing else.

Upvotes: 0

Views: 74

Answers (5)

Juxhin
Juxhin

Reputation: 5600

if(i == 49){
   System.out.println(t.nextInt(100));
}

Will only print the digit on the 50th iteration, when i = 49. That's all your question seems to ask for. Obviously that has to be placed within the for-loop. You can adjust the condition within the if-statement to fit your desired behaviour.

Also as it has already been pointed out. You ought to instantiate Random t only once and that's outside the for-loop. This way you don't break the randomness of the algorithm and you don't unnecessarily instantiate the object multiple times.

Upvotes: 2

Mario
Mario

Reputation: 2505

int last = -1;

for(int i=0;i<50;i++)
{
    Random t = new Random();

    // random integers in [0, 100]
    last = t.nextInt(100);
    //System.out.println(last);
}

// Now take "last" and do whatever you want with it.
doSomething(last);

Upvotes: 0

robin
robin

Reputation: 199

You can declare a variable above the for block and initialize it every time when the loop runs and use it after the for loop finishes:

Random t = null;
for(int i=0;i<50;i++)
{
   t = new Random();
   // random integers in [0, 100]
   System.out.println(t.nextInt(100));
}
if (t != null) {
    // do write operation to text file here
}

Upvotes: 1

thomas77
thomas77

Reputation: 1150

Since you have the index, try this:

for(int i=0;i<50;i++)
{
  Random t = new Random();

   // random integers in [0, 100]
   if(i==49) {
     System.out.println(t.nextInt(100));
   }
}

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234665

More importantly, you must not create a new Random instance on each iteration. That completely ruins the statistical properties of the generator.

To print out the last value, store it and print at the end.

Putting this all together:

{ /*To stop t and n leaking into scope*/
    Random t = new Random();
    int n = 0;
    for (int i=0; i < 50; ++i){ /*I prefer ++i as I'm an old-fashioned cat*/
        n = t.nextInt(100); /*presumably you do something with this number*/
    }
    System.out.println(n);
}

Upvotes: 5

Related Questions