英文:
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());
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论