Reading and storing a string in java

时间:2017-08-30 21:02:22

标签: java string

So let's say I'm given a chess piece that is at location "c4", so it's in the 3rd column and 4th row. How would one go about reading this "c4" string and then marking on the board that a piece is there. I've been thinking one for loop that reads for characters and another that reads for numbers, but not sure how to mark that a piece is in a location like c4. Any ideas/ideas to push me into right direction?

2 个答案:

答案 0 :(得分:2)

您可能希望将这些值存储为2D数组,如下所示:

bool[][] board = new bool[8][8];

至于阅读字符串,有很多方法可以解决它。我会使用charAt取出单个字符,然后将第一个字符放在switch语句中以查找它的数值。

String input = "c4"
int row = Character.getNumericValue(input.charAt(1));
char columnChar = input.charAt(0);
int column;
switch (Character.toLowerCase(input.charAt(1)) {
    case 'a':
        column = 1;
    case 'b':
        column = 2;
    // etc...
}
board[column - 1][row - 1] = true; // Fill the board, subtracting one to account for arrays indexing from zero

在这里,我使用了一系列bool来跟踪,但当然你需要更复杂的东西来跟踪不同的部分。创建ChessPiece类并扩展它以创建每个部分的可能性会很有帮助。

答案 1 :(得分:0)

这实际上取决于你是什么,并且在这种情况下无法保证。你知道第一个角色永远都是一个字母吗?你的人数限制是多少?

如果您确保第一个始终是一个角色,就像棋盘(一个8x8网格),那么你可以做一个简单的myStr.charAt(0)来做到这一点,用那个角色做点什么,然后替换那里的内容并将其余内容转换为la myStr.replace(oldChar, '')并使用Integer.parseInt()进行解析。

如果您的数据无法保证并且更加复杂,那么您希望将字符串分解为多个部分,解析您将其分解为的内容,并对数据执行某些操作。例如,如果我被赋予了字符串"hh88",我将首先找到我的数字开始的位置,将这两个部分分开,然后从那里做一些数据。如果您不保证相同的订单,即"8c"是有效的字符串条目,则同样的想法也适用,这里的区别在于您需要确定每个组件的位置。

相关问题