繁体   English   中英

使用方法通过查找匹配值然后使用不同的输入变量更新来更新二维数组

[英]Using a Method to update a 2D Array by finding a matching value and then updating with a different input variable

假设我有一个名为GameBoard的公共类,它将是一个 4 行 5 列的二维数组。 数组中的空格以 1 到 20 的String值归档。将抽取一张具有名称的卡片(例如King of Spades )。 如果用户输入15我会将其存储在名为userLocationString变量中。 创建一个获取输入位置并使用卡片名称更新数组的方法的最有效方法是什么? for 循环会最有效吗?

public GameBoard() {
    square  = new String[4][5];
    square[0][0] = new String("1");
    square[0][1] = new String("2");
    square[0][2] = new String("3");
    square[0][3] = new String("4");
    square[0][4] = new String("5");
    square[1][0] = new String("6");
    square[1][1] = new String("7");
    square[1][2] = new String("8");
    square[1][3] = new String("9");
    square[1][4] = new String("10");
    square[2][1] = new String("11");
    square[2][2] = new String("12");
    square[2][3] = new String("13");
    square[3][1] = new String("14");
    square[3][2] = new String("15");
    square[3][3] = new String("16");
    square[2][0] = new String(17);
    square[3][0] = new String(18);
    square[2][4] = new String(19);
    square[3][4] = new String(20);

}

到目前为止,我的首选方法看起来像这样,但它在userLocation = board[i][j]下给了我错误代码“类型不匹配:无法将字符串转换为布尔值”

public String[][] updateBoard(String userLocation, Card card, String[][] board) {

    for (int i = 0; i <4; i++)
        {
           for (int j = 0; j < 5; j++)
           {
             if(userLocation = board[i][j]) {

                 board[i][j] = card.name;

             }
           } 
        } 

    return board;

}

所以它不会编译的原因是你的 = 不返回布尔表达式。 == 会,但它仍然不是你想要的,因为你想检查字符串内容是否相同,而不是它们是否是同一个对象,所以使用 .equals。

但是,不,我认为您不想依赖字符串来识别位置。 如果要换卡怎么办? 为什么在不需要时浏览所有内容?

相反,如果 i 是 1 到 20 之间的某个数字,则通过square[(i-1)/5][(i-1)%5]确定数组中的相应点

这应该绕过匹配字符串的问题。

例如,您的构造函数变为:

public GameBoard() {
square  = new String[4][5];
for (int i=1; i<=20;i++){
    square[(i-1)/5][(i-1)%5]=""+i;//initialize with 1 to 20 if you like
}

userLocation是一个int

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM