Tuesday, 15 May 2012

java - strange behaviour with if statement -



java - strange behaviour with if statement -

i'm trying simple, 1 dimension "ships game". i'm stuck on randomly generating ships. have array 10 cells. first ship take 3 cells, sec 2 , 3rd 1. made ship object constructor d = dlugosc (their length). i'm writing method randomly place them in array. here whole, short code:

package statki1; import java.util.arrays; import java.util.random; import java.util.scanner; public class statki1 { static int[] array = new int[10]; static int dlugosc; static random r = new random(); //constructor ships public statki1(int d) { dlugosc = d; } //ships objects static statki1 xxx = new statki1(3); static statki1 xx = new statki1(2); static statki1 x = new statki1(1); //method randomly place ships public static void losowanie3() { int s = r.nextint(array.length); array[s] = 2; if (array[0] == 2) { array[s+1] = 2; array[s+2] = 2; array[s+3] = 1; } system.out.println(s); } public static void main(string[] args) `enter code here`{ scanner input = new scanner(system.in); int choose; xxx.losowanie3(); system.out.println(arrays.tostring(array)); } }

and works fine , array looks this:

[2, 2, 2, 1, 0, 0, 0, 0, 0, 0]

but in main sth this

xxx.losowanie3; xx.losowanie3; x.losowanie3

so need add together status method, should this:

if (array[0] == 2 & dlugosc == 3) { array[s+1] = 2; array[s+2] = 2; array[s+3] = 1; }

but doesn't work. if array[0] == 2 array looks this:

[2, 0, 0, 0, 0, 0, 0, 0, 0, 0]

and should this: [2, 2, 2, 1, 0, 0, 0, 0, 0, 0]

can help me solve problem? regards

the if statement never executes when add together statement:

if (array[0] == 2 & dlugosc == 3) { array[s+1] = 2; array[s+2] = 2; array[s+3] = 1; } system.out.println("value of dlugosc " + xxx.dlugosc);

this prints out output:

the value of dlugosc 1 [2, 0, 0, 0, 0, 0, 0, 0, 0, 0]

for if statement execute, variable "s" has equal 0 , variable "dlugosc" has equal 3. when random number assigned variable "s" 0 (which had run programme multiple times 0), if statement not execute because value of variable "dlugosc" 1.

you marked variable "dlugosc" static variable. means there 1 re-create of variable in class.

the problem seems in code block:

//ships objects static statki1 xxx = new statki1(3); static statki1 xx = new statki1(2); static statki1 x = new statki1(1);

the lastly line in code block assigns value of 1 variable "dlugosc" , since there 1 re-create of variable, if statement fail execute. when commented out sec , 3rd line as:

//ships objects static statki1 xxx = new statki1(3); // static statki1 xx = new statki1(2); // static statki1 x = new statki1(1);

then ran programme multiple times until variable "s" equal 0. prints desired output:

the value of dlugosc 3 [2, 2, 2, 1, 0, 0, 0, 0, 0, 0]

maybe should modify programme every object has own re-create of variable.

java arrays if-statement

No comments:

Post a Comment