if语句的奇怪行为

时间:2014-11-11 15:06:27

标签: java arrays if-statement

我试图做一个简单的,一个维度的游戏"。我被困在随机发电的船上。我有10个单元格的数组。第一艘船将需要3个单元,第二艘和第三艘1.所以我将船作为一个对象,构造函数为d = dlugosc(它们的长度)。现在我正在编写一个方法,将它们随机放入我的数组中。这是我的全部短代码:

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 for ships
public Statki1(int d) {
    dlugosc = d;
}

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

//method which will 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));

    }
}

现在它工作正常,我的数组看起来像这样:

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

但在主要方面我会做这样的事情

xxx.losowanie3;
xx.losowanie3;
x.losowanie3

所以我需要为我的方法添加一个条件,所以它应该是这样的:

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

但它不起作用。现在如果array [0] == 2我的数组看起来像这样:

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

应该是这样的:[2, 2, 2, 1, 0, 0, 0, 0, 0, 0]

任何人都可以帮我解决这个问题吗? 此致

2 个答案:

答案 0 :(得分:4)

这是因为你的s值可以是0-10之间的任何值。

因为s可以是数组大小的任何数字,只有当s == 0时,你的代码才会按照你想要的方式运行。

也许你应该重新考虑选择s而不是使用随机类来生成s

的值

答案 1 :(得分:0)

添加语句时,if语句实际上永远不会执行:

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

打印出输出:

The value of dlugosc is 1
[2, 0, 0, 0, 0, 0, 0, 0, 0, 0]

对于要执行的if语句,变量" s"必须等于0和变量" dlugosc"必须等于3.即使分配给变量的随机数" s"是0(我必须多次运行程序才能得到0),if语句不会执行因为变量的值" dlugosc"是1。

您标记了变量" dlugosc"作为静态变量。这意味着该类中只有一个变量副本。

问题似乎出现在代码块中:

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

此代码块中的最后一行将值1赋给变量" dlugosc"由于只有一个变量副本,if语句将无法执行。 当我将第二行和第三行注释掉时:

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

然后多次运行程序,直到变量" s"等于0.这将打印所需的输出:

The value of dlugosc is 3
[2, 2, 2, 1, 0, 0, 0, 0, 0, 0]

也许你应该修改程序,以便每个对象都有自己的变量副本。

相关问题