-1

I'm thinking of making a variable calculate every time I call/use them? Is that even possible?

int myvalue = rn.nextInt(100 - 1 + 1) + 1;
System.out.println("call myvalue: " + myvalue);
System.out.println("call myvalue again: " + myvalue);
System.out.println("call myvalue the third time: " + myvalue);
Noob
  • 37
  • 7

2 Answers2

1

Option 1, create a method:

static int myvalue(Random rn) {
    return rn.nextInt(100 - 1 + 1) + 1;
}
System.out.println("call myvalue: " + myvalue(rn));
System.out.println("call myvalue again: " + myvalue(rn));
System.out.println("call myvalue the third time: " + myvalue(rn));

Option 2, use a lambda expression (Java 8+):

IntSupplier myvalue = () -> rn.nextInt(100 - 1 + 1) + 1;
System.out.println("call myvalue: " + myvalue.getAsInt());
System.out.println("call myvalue again: " + myvalue.getAsInt());
System.out.println("call myvalue the third time: " + myvalue.getAsInt());
Andreas
  • 154,647
  • 11
  • 152
  • 247
0

Create a method which will return int like this:

static int myvalue()
{ 
    Random rn= new Random();  
    return rn.nextInt(100 - 1 + 1) + 1;
}

and call it in System.out.println():

public static void main(String[] args) 
{                       
  System.out.println("call myvalue: " + myvalue());
  System.out.println("call myvalue again: " + myvalue()); 
  System.out.println("call myvalue the third time: " + myvalue());
}    
Ankit
  • 682
  • 1
  • 6
  • 14