Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare the current value with previous value in a loop in java

Tags:

java

for-loop

How do I compare the current value with previous value in for loop in java and determine if they are different?

Here I have for loop that loop every time I click the mouse. Therefore i depends on where I click.

Here both the current i and the previous i are equal to 3.

https://www.dropbox.com/s/55dao9a9r8o4yis/Untitled%20picture%206.png

Here the current i equal to 7 and the previous i equal to 11.

https://www.dropbox.com/s/pj38l23ughn6ey9/Untitled%20picture%207.png

I am trying to make if statement to compare the two values of previous i with the current i.

Here is my for loop

public void mousePressed() {      
    if (state == 0) {            
        for (int i = 0; i < 6; i++) {
            if (mouseX >= cards[i].x && mouseX <= cards[i].x + cards[i].WIDTH && mouseY >= cards[i].y && mouseY <= cards[i].y + cards[i].HEIGHT) {
                cards[i].flip();                     
            }               
        }
like image 478
Ali Baker Avatar asked Nov 19 '25 14:11

Ali Baker


2 Answers

Start "i" with "1", smth. like:

    for (int i = 1; i < 6; i++) {
        if (cards[i].equals(cards[i-1])) {
            cards[i].flip();                     
        }  
    }
like image 117
pasha701 Avatar answered Nov 22 '25 04:11

pasha701


This is what you are looking for

int currentValue=0;
    int lastValue=0;

    for(int i=0;i<10;i++){
        currentValue =i;

        if(i>0){
            System.out.println(" Current Value is "+currentValue+" Last Value is "+lastValue);
        }   

        lastValue=currentValue;
    }
like image 33
Dark Knight Avatar answered Nov 22 '25 02:11

Dark Knight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!