gpt4 book ai didi

java - Java中如何将棋盘格坐标转换为对应的行号和列号?

转载 作者:行者123 更新时间:2023-11-30 06:56:36 25 4
gpt4 key购买 nike

这是我第一次使用java,所以请多多包涵。想象一个 26x26 的棋盘(或国际象棋棋盘)。我需要知道如何正确地将棋盘格的坐标转换为相应的行号和列号。例如,z19对应第26列第19行的一 block 。我已经使用哈希表得到了大部分代码,但我遇到的问题是当我输入一个两位数时,我得到的输出是两个数字,但是分开的。例如:

Input: z19
Output:
26
1
9

我该如何解决这个问题?这是我的方法:

public static void hash(String coordinates){

HashMap hash = new HashMap();
hash.put("a", 1);
hash.put("b", 2);
hash.put("c", 3);
hash.put("d", 4);
hash.put("e", 5);
hash.put("f", 6);
hash.put("g", 7);
hash.put("h", 8);
hash.put("i", 9);
hash.put("j", 10);
hash.put("k", 11);
hash.put("l", 12);
hash.put("m", 13);
hash.put("n", 14);
hash.put("o", 15);
hash.put("p", 16);
hash.put("q", 17);
hash.put("r", 18);
hash.put("s", 19);
hash.put("t", 20);
hash.put("u", 21);
hash.put("v", 22);
hash.put("w", 23);
hash.put("x", 24);
hash.put("y", 25);
hash.put("z", 26);
hash.put("1", 1);
hash.put("2", 2);
hash.put("3", 3);
hash.put("4", 4);
hash.put("5", 5);
hash.put("6", 6);
hash.put("7", 7);
hash.put("8", 8);
hash.put("9", 9);
hash.put("10", 10);
hash.put("11", 11);
hash.put("l2", 12);
hash.put("13", 13);
hash.put("14", 14);
hash.put("15", 15);
hash.put("16", 16);
hash.put("17", 17);
hash.put("18", 18);
hash.put("19", 19);
hash.put("20", 20);
hash.put("21", 21);
hash.put("22", 22);
hash.put("23", 23);
hash.put("24", 24);
hash.put("25", 25);
hash.put("26", 26);
String word = new String(coordinates);
char array[] = word.toCharArray();
for(char c: array) {
System.out.println(hash.get(String.valueOf(c)));
}
}

有一件事我忘记提及:我还希望能够同时输入不同的坐标点。例如,如果我输入:

Input: a4c23d17

我希望它输出这个:

1
4
3
23
4
17

最佳答案

你把问题过于复杂化了。试试这个:

// split coordinates string into (x, y) pairs by using
// regex lookahead to find the next alphabetical character
for (String coord : "a4c23d17".split("(?=[a-z])")) {
// subtract the ascii value of 'a' from
// the first char to get the numeric offset
System.out.println(coord.charAt(0) - 'a' + 1);
// parse the remainder as an integer
System.out.println(Integer.parseInt(coord.substring(1)));
}

关于java - Java中如何将棋盘格坐标转换为对应的行号和列号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41666801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com