【问题标题】:Getting the latest Int 2 values of a constantly changing Integer获取不断变化的 Integer 的最新 Int 2 值
【发布时间】:2018-06-22 14:00:47
【问题描述】:

我正在尝试检查不断变化的速度整数中的值,我要检查的值是当前值和之前的值,我有这段代码,但由于某种原因它不起作用。 我的问题是如何有效地保存不断变化的速度整数的最新 2 个值

这是我的代码

 int CurrentValue; // The Integer is already defined and initialized, this is the latest value of it
 int PriorValue; // this value is the one that was prior to the current one
 CurrentValue = ChangingInt; // here we save the current Speed value in ChangingInt

 if (CurrentValue != ChangingInt){
     PriorValue = CurrentValue; /* replacing the CurrentValue value as the prior one
     since it has changed according to the if statement */
 }

【问题讨论】:

    标签: java android integer


    【解决方案1】:

    您可以添加一个temp 变量来存储CurrentValue 的值。

    int CurrentValue;
    int PriorValue;
    int temp = CurrentValue; //Add a temp variable to store CurrentValue.
    CurrentValue = ChangingInt;        
    PriorValue = temp;
    

    【讨论】:

    • 所以我需要使用当前值的临时值吗?然后让它等于前一个?但如果是这种情况,那么所有值将始终相同,因为 temp = CurrentValue 然后 PriorValue = temp,它不等同于做 PriorValue = CurrentValue,因为它是相同的值?
    • 让我们运行一个示例。假设CurrentValue = 1, PriorValue = 2。现在一个新的ChangingInt = 3 值进来了,然后我们有了temp = CurrentValue = 1, CurrentValue = ChangingInt = 3, PriorValue = temp = 1。所以最后我们得到CurrentValue = 3, PriorValue = 1。对吗?
    • 根据你的逻辑,当CurrentValue = 1, PriorValue = 2,和一个新的ChangingInt = 3值进来时,你会得到CurrentValue = ChangingInt = 3,而CurrentValue != ChangingInt总是false
    • 啊,我明白了,但是我没有初始化CurrentValue的值,在第一次运行时,这段代码第一次运行会出现NullPointerException错误吗?或者我可以将int temp = CurrentValue; 包装在 if 语句中以解决问题
    • 这里有两个选择:使用Integer 而不是int,因为null 可以用于Integer;或将CurrentValue 初始化为0-1 等值。
    【解决方案2】:
    int ChangingInt = ...          // ChangingInt = A, PriorValue = B, CurrentValue = C
    ...
    int PriorValue = CurrentValue  // ChangingInt = A, PriorValue = C, CurrentValue = C
    int CurrentValue = ChangingInt // ChangingInt = A, PriorValue = B, CurrentValue = A
    

    运行后我们不需要PriorValue,因为我们只需要最后两个值,所以我们应该首先重新分配PriorValue,将其更改为CurrentValue(因为CurrentValue需要成为新的@987654326 @)。然后,我们可以把CurrentValue改成ChangingInt

    【讨论】:

      猜你喜欢
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-23
      • 1970-01-01
      • 1970-01-01
      • 2011-06-24
      • 1970-01-01
      相关资源
      最近更新 更多