带有char数组的循环Java for-function

问题描述 投票:0回答:4

我在这里遇到了一个循环问题,我正在编写一个脚本,它将接收让我们说字符串“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'}};

首先,我将String传递给char数组:

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实例,将数组转换为String

String second = new String(tab);

我把这个String变成了一个双

double finalC = Double.parseDouble(second);

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

以下是字符串“abcd”的循环之后的制表符数组内部的示例:

Indice : 0 value: 0
Indice : 1 value: 1
Indice : 2 value: c
Indice : 3 value: d
java arrays for-loop multidimensional-array
4个回答
2
投票

凯文克鲁伊森解决了你的问题,但你可以更多:

使用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());

0
投票

问题在于你的内循环:twoD.length是2,因为twoD包含你的两个内部字符数组。

你应该使用twoD[0].length代替:

for(int c=0; c<tab.length; c++) {
  for(int z=0; z<twoD[0].length; z++) {
    ...

但是,由于您使用全部十位数字,或许最好使用它:

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++) {
  for(int z=0; z<amountOfDigitsUsed; z++) {
    ...

无论你是否使用硬编码的twoD转换和amountOfDigits使用与否。在您当前的实施中,您的twoD.length为2,导致您现在遇到的问题。


0
投票

你的twoD数组的长度是2.你的第二个循环应该从z = 0迭代到twoD[0].length

尝试有意义地命名变量,以便更容易找到这样的错误。还要查看foreach循环,这样您就不必担心索引了。 Java Maps可能更适合将字符映射到数字。


0
投票

因为在您的情况下,字符似乎随着int值递增,所以您根本不需要地图。您可以将字符强制转换为int,然后减去a的int值。这是B_Osipiuk答案的略微变化:

String toEncode = "abcd";
char[] chars = toEncode.toCharArray();
StringBuilder sb = new StringBuilder();
for(char c : chars){
    int newInt = c - 'a';
    if (newInt < 0 || newInt > ('j'-'a')) {
        continue; //or do something else, e.g throw exception;
    }
    sb.append(newInt);
}

System.out.println(sb.toString());
© www.soinside.com 2019 - 2024. All rights reserved.