Java, infinite while loop, incrementation

in the following sample Java program, I get an infinite loop, and I cannot understand why:

public class Time {

    public static int next(int v) {
        return v++;
    }

    public static void main(String[] args) {

        int[] z = {3, 2, 1, 0};

        int i = 1;

        while(i < 4) {
            System.out.println(z[i]/z[i]);
            i = next(i);
        }
    }
}

The next () method is called in the while loop, and each time you need to increase it by 1: next () should return i ++, and the value of me in the while loop should increase by one.

Why can it be the cause of an endless cycle? Thanks.

+3
source share
7 answers

You are using post incrementation. This should work:

public static int next(int v) {
        return v+1; //or ++v
    }

so basically your next function in your example returns the same number, not increment it.

+17
source

Definition for v ++:

Return the current value of v then add one to v

v , main, , . v .

++ v. :

Add one to v, then return the new value
+9

- .

:

int a = 1;
int b = a++; // sets b to to 1 THEN increments a.

// a now equals 2.

int c = ++a; // increments a THEN stores the value in c, c = 3.

, int ++, , . , :

while (expression) {
// code...
intValue++;
}

, , .

public static int someMethod(int n) {
return n++;  
}

n, . int n, , , , , n. , , n reset , .

+5

, :

for(int i = 0; i < 4; i++){
    System.out.println(z[i]/z[i]);
}

... :

for(int x : z){
    System.out.println(x / x);
}

...?

+3
public static int next(int v) {
        return ++v;
}

, Java .

+1

public static int next(int v) {
        return v + 1;
}

v ++ , v .

, ++ v v ++ return , ++ v, . , undefined .

+1

post increment work, , bcas "0" . 0/0 , , "0"

0

Source: https://habr.com/ru/post/1702525/


All Articles