如何重新计算变量?

huangapple go评论60阅读模式
英文:

How to recalculate variable?

问题

我正在考虑每次调用/使用它们时都计算一个变量,这是否可能?

int myvalue = rn.nextInt(100 - 1 + 1) + 1;
System.out.println("调用myvalue: " + myvalue);
System.out.println("再次调用myvalue: " + myvalue);
System.out.println("第三次调用myvalue: " + myvalue);
英文:

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);

答案1

得分: 1

选项1,创建一个方法:

static int myvalue(Random rn) {
    return rn.nextInt(100 - 1 + 1) + 1;
}
System.out.println("调用myvalue: " + myvalue(rn));
System.out.println("再次调用myvalue: " + myvalue(rn));
System.out.println("第三次调用myvalue: " + myvalue(rn));

选项2,使用lambda表达式 (Java 8+)

IntSupplier myvalue = () -> rn.nextInt(100 - 1 + 1) + 1;
System.out.println("调用myvalue: " + myvalue.getAsInt());
System.out.println("再次调用myvalue: " + myvalue.getAsInt());
System.out.println("第三次调用myvalue: " + myvalue.getAsInt());
英文:

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());

答案2

得分: 0

创建一个方法,将会返回像这样的 int 值:

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

并在 System.out.println() 中调用它:

public static void main(String[] args) 
{   					
  System.out.println("调用 myvalue: " + myvalue());
  System.out.println("再次调用 myvalue: " + myvalue()); 
  System.out.println("第三次调用 myvalue: " + myvalue());
}    
英文:

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());
}    

huangapple
  • 本文由 发表于 2020年10月12日 12:46:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/64311822.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定