Java for 循环与 char 数组 dis-function

标签 java arrays for-loop multidimensional-array

我在这里遇到了一个循环问题,我正在编写一个脚本,该脚本将接收字符串“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/

相关文章:

c - 用用户输入填充数组

arrays - Swift 闭包数组 - 查找元素

javascript - 在 JavaScript 中,如何将多个数组转换为 HTML 表并在 for 循环 JSON 对象时打印它们

java - 标签 'select' ,字段 'list' ,名称 'uuid' : The requested list key 'deptList' could not be resolved as a collection/array/map/enumeration/iterator type

java - 如何使用 selenium 对点击时触发的事件进行自动化分析测试?

java - 在导出的 Spring 项目中打包 Spring Jars - 更好的方法?

for-loop - 是否可以在 Kotlin 中编写一个 for 循环,在迭代过程中我可以将索引更改为我想要的任何值?

java - 阿姆斯特朗数java

java - 从Excel读取数据并删除空白行并从行中获取数据添加到数组列表中的列表

c++ - 不适合( auto && v : arr ) clobber the contents of the array?