猿问

带有字符数组功能的Java for循环

我在这里遇到了循环问题,我正在编写一个脚本,该脚本将接收字符串“geij”或“abab”,并且必须将其转换为“6478”或“0101”之类的双精度值。由于二维数组,我进行了从字母到数字的转换:


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);

我把这个 String 变成了 double


double finalC = Double.parseDouble(second);

问题在于这个循环,如果字符串 crypt 是“abab”,则循环将返回 0101,因为它应该返回 0101,但是如果字符串包含来自两个数组的第一个数组中的“a”或“b”之后的任何字母 -维数组,例如字符串“geij”,程序将简单地返回“geij”。我不明白为什么这个程序没有比 b 更进一步,它开始给我一个蛋头。如果有人有想法,我将不胜感激!


以下是字符串 "abcd" 循环之后的选项卡数组内部示例:


Indice : 0 value: 0

Indice : 1 value: 1

Indice : 2 value: c

Indice : 3 value: d


人到中年有点甜
浏览 234回答 3
3回答

慕无忌1623718

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){&nbsp; &nbsp; int newInt = encoding.getOrDefault(c, -5); //-5 is just a flag that there is no char to encode&nbsp; &nbsp; if(newInt == -5){&nbsp; &nbsp; &nbsp; &nbsp;continue; //or do something else, e.g throw exception;&nbsp; &nbsp; }&nbsp; &nbsp; 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());

慕尼黑8549860

你的 twoD 数组的长度是 2。你的第二个循环应该从z = 0到迭代twoD[0].length。尝试有意义地命名您的变量,以便更容易找到这样的错误。还要检查 foreach 循环,这样您就不必担心索引。Java Maps 可以更好地将字符映射到数字。

墨色风雨

问题出在您的内部循环中:twoD.length是 2,因为twoD包含您的两个内部字符数组。你应该使用twoD[0].length:for(int c=0; c<tab.length; c++) {&nbsp; for(int z=0; z<twoD[0].length; z++) {&nbsp; &nbsp; ...但是,由于您使用的是所有十位数字,因此最好改用它:char twoD[][] = {{'a','b','c','d','e','f','g','h','i','j'}, {'0','1','2','3','4','5','6','7','8','9'}};int amountOfDigitsUsed = 10; // Equal to `twoD[0].length` or `twoD[1].length`.for(int c=0; c<tab.length; c++) {&nbsp; for(int z=0; z<amountOfDigitsUsed; z++) {&nbsp; &nbsp; ...无论您是否使用硬编码twoD转换和amountOfDigits使用与否。在您当前的实现中,您twoD.length是 2,导致您现在遇到的问题。
随时随地看视频慕课网APP

相关分类

Python
我要回答