Java Array未正确填充

时间:2015-02-13 06:58:27

标签: java arrays

我有以下代码,我似乎无法调试。我将对象passenger添加到seat对象中的row对象中。如果seat被占用,它将从第一个row开始,遍历所有seats并向其添加passenger。但是,如果我remove以前拥有seat,则添加新的passenger。新passenger应占据之前拥有的seat。情况并非如此,新的passenger会占用下一个seat。我的假设是我的firstClassRow.get(i)是从最近的index开始,而不是从0开始。

这里只是一个基本的例子

1A filled 1B unfilled(should fill here)
2A filled 2B filled
3A filled 3B unfilled(but fills here)



public void addUser(Passenger p)
{
    Rows tempR;
    boolean result = true;
    int i = 0;


    while(result == true)
    {
        tempR = firstClassRow.get(i);
        if(tempR.check(p) == true)
        {
            tempR.addPassenger(p);
            result = false;
        }
        else
        {
            i = i + 1;
            if (i < number)
            {
                result = true;
            }
            else
            {
                result = false;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

检查此示例可能会有所帮助

  public static void main(String args[]) {
    String ll[][] = new String[2][2];
    System.out.println(ll.length);
    System.out.println(ll[1].length);

    for (int i = 0; i < ll.length; i++)
        for (int j = 0; j < ll[1].length; j++)
            ll[i][j] = "true";
    System.out.println();
    System.out.println("All seats are occupied");
    display(ll);
    ll[0][1] = "false";
    ll[1][1] = "false";
    System.out.println();
    System.out.println("Two seats emptied");
    display(ll);
    // adding new one
    System.out.println();
    System.out.println("Adding new passenger");
    addPassenger(ll);
    display(ll);

    System.out.println();
    System.out.println("Adding new passenger");
    addPassenger(ll);
    display(ll);
}

static void display(String a[][]) {

    for (int i = 0; i < a.length; i++)
        for (int j = 0; j < a[1].length; j++)
            System.out.println(i + "" + j + " :: " + a[i][j]);
}

static void addPassenger(String a[][]) {
    boolean result = false;
    for (int i = 0; i < a.length; i++)
        for (int j = 0; j < a[1].length; j++) {
            if (a[i][j] == "false") {
                a[i][j] = "true";
                result = true;
            }
            if (result)
                break;
        }
}

 Output:
 All seats are occupied
 00 :: true
 01 :: true
 10 :: true
 11 :: true

 Two seats emptied
 00 :: true
 01 :: false
 10 :: true
 11 :: false

 Adding new passenger
 00 :: true
 01 :: true
 10 :: true
 11 :: false

 Adding new passenger
 00 :: true
 01 :: true
 10 :: true
 11 :: true