【问题标题】:Comparing an int to its old value in Java将 int 与其在 Java 中的旧值进行比较
【发布时间】:2016-04-08 01:46:27
【问题描述】:

我正在编写一些代码,我需要确定在最后一个循环中整数的变化量。

我的代码:

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import com.leapmotion.leap.*;

import java.io.IOException;

import com.leapmotion.leap.Gesture.State;
import java.io.OutputStream;

import com.leapmotion.leap.Controller;
import com.leapmotion.leap.Frame;
import com.leapmotion.leap.Listener;
import java.lang.Math;

class SampleListenerMain extends Listener {

public void onInit(Controller controller) {
System.out.println("Initialized");
}

public void onConnect(Controller controller) {
System.out.println("Connected");
controller.enableGesture(Gesture.Type.TYPE_SWIPE);
controller.enableGesture(Gesture.Type.TYPE_CIRCLE);
controller.enableGesture(Gesture.Type.TYPE_SCREEN_TAP);
controller.enableGesture(Gesture.Type.TYPE_KEY_TAP);


}

public void onDisconnect(Controller controller) {
System.out.println("Disconnected");
}

public void onExit(Controller controller) {
System.out.println("Exited");
}
public void onFrame(Controller controller) {


Frame frame = controller.frame();

Hand hand = frame.hands().rightmost();
float positionx = hand.palmPosition().getX();
System.out.println("X: " + positionx);

float positiony = hand.palmPosition().getY();
System.out.println("Y:" + positiony);

float positionz = hand.palmPosition().getZ();
System.out.println("Z: " + positionz);

System.out.println("Hands: " + frame.hands().count());

int in_min = -117;
int in_max = 117;
int out_min = 900;
int out_max = 1900;
int in_min2 = -73;
int in_max2 = 73;

int positionmapx = (int) ((positionx - in_min) * (out_max - out_min) /     (in_max - in_min)) + out_min;
int positionmapy = (int) ((positiony - in_min) * (out_max - out_min) / (in_max - in_min)) + out_min;
int positionmapz = (int) ((positionz - in_min) * (out_max - out_min) / (in_max2 - in_min)) + out_min;


if (frame.hands().count() == 0) {
    LeapDrone.writeToArduino("0");
}


int posmapxold = 0;
int posmapyold = 0;
int posmapzold = 0;


String data = Integer.toString(positionmapy)+":"+     Integer.toString(positionmapx)+":"+Integer.toString(positionmapz);

System.out.println("data: " + data);


System.out.println("Old X: " + posmapxold);

System.out.println("Difference X: " + Math.abs(positionmapy - posmapyold));

if (Math.abs(positionmapx - posmapxold) >= 25) {


    LeapDrone.writeToArduino(data);

    try {
        Thread.sleep(50);
    } catch (InterruptedException e) {

        e.printStackTrace();
    }

}

if (Math.abs(positionmapy - posmapyold) >= 25) {


    LeapDrone.writeToArduino(data);

    try {
        Thread.sleep(50);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

if (Math.abs(positionmapz - posmapzold) >= 25) {


    LeapDrone.writeToArduino(data);

    try {
        Thread.sleep(50);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

posmapxold = positionmapx;
posmapyold = positionmapy;
posmapzold = positionmapz;

System.out.println("New-Old X: " + posmapxold);

try {
    Thread.sleep(100);
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

GestureList gestures = frame.gestures();
for (int i = 0; i < gestures.count(); i++) {
    Gesture gesture = gestures.get(i);



}
}
}

   class LeapDrone {
static OutputStream out = null;

public static void main(String[] args) {
//Connect to Arduino BT

try
{
(new LeapDrone()).connect("/dev/cu.usbmodem1421");
}
   catch ( Exception e )
{
    e.printStackTrace();
System.exit(0);
}

// Create a sample listener and controller
SampleListenerMain listener = new SampleListenerMain();
Controller controller = new Controller();

// Have the sample listener receive events from the controller
controller.addListener(listener);
// Keep this process running until Enter is pressed
System.out.println("Press Enter to quit...");
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}

// Remove the sample listener when done
controller.removeListener(listener);
}

void connect ( String portName ) throws Exception {

CommPortIdentifier portIdentifier =     CommPortIdentifier.getPortIdentifier(portName);
if ( portIdentifier.isCurrentlyOwned() )
{
System.out.println("Error: Port is currently in use");
}
else
{
CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);

if ( commPort instanceof SerialPort )
{
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
out = serialPort.getOutputStream();
}
else
{
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}

public static void writeToArduino(String data)
{
String tmpStr = data;
byte bytes[] = tmpStr.getBytes();
try {
out.write(bytes);
} catch (IOException e) { }
}
}

例如,我有整数 i。我想运行一个循环,看看我改变了多少(在我的例子中,我被分配给一个改变每个循环的 x 坐标)。一旦在该循环中设置了 i,我将整数 j 设置为等于 i。然后我需要将 i 与 j 进行比较。

问题是我必须将 j 定义为等于某个值才能对其进行初始化。这意味着,例如,如果我通过将 j 设置为 0 来初始化它,那么每次我的代码循环时它都会重置为 0,这意味着我无法将 i 与其旧值(应该是 j)进行比较。 .....

我尝试使用“for”语句,但出现错误,因为稍后在我的代码中比较 i 和 j 时,它说 j 尚未初始化......我想是因为 for 循环中的代码没有不一定要在程序的开头运行?

抱歉这个令人困惑的问题......我很难解释!

非常感谢任何帮助!!!

【问题讨论】:

    标签: java eclipse for-loop integer


    【解决方案1】:

    如果不看一些示例代码,很难提供答案,但您应该能够将之前的值初始化为循环外的初始值。

    例如:

    // Initialize our previous value to be the current value right off the bat
    previousValue = currentValue;
    
    for (int index = 0; index < whatever; index++) {
    
       // Do something that changes the value
       currentValue = someNewValue();
    
       // Calculate our delta
       delta = currentValue - previousValue;
    
       // Set our previous value to the new current value
       previousValue = currentValue;
    
    }
    

    如果 currentValue 由于某种原因只能在循环中计算,那么您可以为第一次迭代添加一个特殊情况,方法是使用 Object 类型 Integer 而不是原始 int 类型的前一个值null 值表示它的第一次迭代,或者带有一个布尔标志,如下所示:

    boolean firstIteration = true;
    
    for (int index = 0; index < whatever; index++) {
    
       currentValue = someNewValue();
    
       if (firstIteration) {
    
          // Our first iteration has a zero delta
          delta = 0;
          firstIteration = false;
    
       } else {
    
          // Subsequent iterations compare the previous value
          delta = currentValue - previousValue;
    
       }
    
       previousValue = currentValue;
    
    }
    

    【讨论】:

      【解决方案2】:

      如果你想在它再次循环时访问它,你不应该使用局部变量。如果变量不是本地的,则不需要初始化它。

      例如,在循环之前你有int j = 0,那么,每次循环迭代都不会重置它。

      例如:

      int j = 0;
      for(int i=0; i<someVariable; i++){
          //do code
      
          //compare i to j
      }
      

      【讨论】:

      • 我试着把它放在代码的'init'函数中,但是,它仍然给出错误......
      • 不要在init函数中设置,在实际类启动中设置即可。
      • class SampleListenerMain extends Listener { int j 0; public void onInit(Controller controller) {...
      • 谢谢。看来我只是愚蠢......我只是把'public int j = 0;'在循环之前。谢谢。
      猜你喜欢
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-02
      • 1970-01-01
      • 2020-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多