【问题标题】:How to recalculate variable?如何重新计算变量?
【发布时间】:2021-01-26 09:51:40
【问题描述】:

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

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

【问题讨论】:

标签: java


【解决方案1】:

方案一,创建方法:

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

选项 2,使用 lambda 表达式(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】:

    创建一个返回 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("call myvalue: " + myvalue());
      System.out.println("call myvalue again: " + myvalue()); 
      System.out.println("call myvalue the third time: " + myvalue());
    }    
    

    【讨论】:

      猜你喜欢
      • 2016-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-21
      • 2019-08-18
      • 1970-01-01
      • 2018-10-28
      • 1970-01-01
      相关资源
      最近更新 更多