我在这里遇到了一个循环问题,我正在编写一个脚本,该脚本将接收字符串“geij”或“abab”,并且必须将其转换为“6478”或“0101”等 double 值”。感谢二维数组,我完成了从字母到数字的转换:
String crypt = "geij";
char twoD[][] = {{'a','b','c','d','e','f','g','h','i','j'}, {'0','1','2','3','4','5','6','7','8','9'}};
首先,我将字符串传递到字符数组中:
char tab[] = crypt.toCharArray();
然后我使用循环将字母转换为数字:
for(int c=0;c<tab.length;c++) {
for(int z=0;z<twoD.length;z++) {
if(tab[c] == twoD[0][z]) {
tab[c] = twoD[1][z];
}
}
然后我创建一个名为“second”的新字符串实例,将数组转换为字符串
String second = new String(tab);
我把这个字符串变成了 double
double finalC = Double.parseDouble(second);
问题出在这个循环上,如果字符串 crypt 是“abab”,则循环将按预期返回 0101,但如果字符串包含第一个数组中“a”或“b”之后的任何字母二维数组,例如字符串“geij”,程序将简单地返回“geij”。 我不明白为什么这个程序没有比 b 更进一步,而且它开始让我感到困惑。如果有人有想法,我将不胜感激!
以下是字符串“abcd”循环后选项卡数组内部的示例:
Indice : 0 value: 0
Indice : 1 value: 1
Indice : 2 value: c
Indice : 3 value: d
最佳答案
Kevin Cruijssen 解决了您的问题,但您还可以:
使用HashMap来解决这个问题。目前,您的算法时间复杂度为O(n*m)(n 基字符串长度,m - 表中的字母数量),因为您必须为每个字母迭代整个字母数组。
使用 HashMap,您可以在 O(1) 中找到正确的字母。快得多。所以现在你的算法具有O(n)时间复杂度。
简单的例子:
Map<Character, Integer> encoding = new HashMap<>();
encoding.put('a', 0);
encoding.put('b', 1);
encoding.put('c', 2);
encoding.put('d', 3);
String toEncode = "abcd";
char[] chars = toEncode.toCharArray();
StringBuilder sb = new StringBuilder();
for(char c : chars){
int newInt = encoding.getOrDefault(c, -5); //-5 is just a flag that there is no char to encode
if(newInt == -5){
continue; //or do something else, e.g throw exception;
}
sb.append(newInt);
}
System.out.println(sb.toString());
//Parse double if you want, but remember that what *Nikolas* said in the comments under your post.
//Double.parseDouble(sb.toString());
关于Java for 循环与 char 数组 dis-function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52365298/