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.
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.
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
- .
:
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 , .
, :
for(int i = 0; i < 4; i++){ System.out.println(z[i]/z[i]); }
... :
for(int x : z){ System.out.println(x / x); }
...?
public static int next(int v) { return ++v; }
, Java .
public static int next(int v) { return v + 1; }
v ++ , v .
, ++ v v ++ return , ++ v, . , undefined .
post increment work, , bcas "0" . 0/0 , , "0"
Source: https://habr.com/ru/post/1702525/More articles:How to create a custom GControl - google-mapsIs LINQ dynamic possible to dynamically specify a from clause? - .netunmanaged / managed interop - problem with passing int [] - c #How to create stateful portal page in jquery user interface? - javascriptcreate my_printf that sends data for both sprintf and regular printf? - cHow to check the restrictions between two tables when pasting into a third table that refers to two other tables? - sqlThe easiest way to install 100s of files in a Visual Studio installation project - rPHP Constant не существует: Уведомление - phpCan you work on a project for more than 10 years without releasing anything? - project-managementhttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1702530/java-nio-sending-large-messages-quickly-leads-to-truncated-packets-and-data-loss&usg=ALkJrhhe5KH1XNJhsgzgIKJm_T42OQdOoAAll Articles