java - 具有字符数组功能的 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'}};
首先,我将 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 second = new String(tab);
我把这个字符串变成了双
double finalC = Double.parseDouble(second);
问题在于这个循环,如果 String crypt 是“abab”,则循环将按预期返回 0101,但如果 String 包含两个数组的第一个数组中的“a”或“b”之后的任何字母 -维数组,例如字符串“geij”,程序将简单地返回“geij”。我不明白为什么该程序没有比 b 走得更远,而且它开始让我感到头疼。如果有人有想法,我将不胜感激!
以下是字符串 "abcd" 循环后 tab 数组内部的示例:
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());
推荐阅读
- vba - 如何分配箭头键ti图像以在用户周围移动
- postgresql - Kubernetes Citus setup with individual hostname/ip
- c# - 将 ResourceDictionary 与 WPF 中的其他样式一起使用
- python - 在熊猫中,按行值分组column1,然后如何合并column2并在其他colum3上找到最小值?
- linux - 进行系统调用时检测键盘中断的linux选项
- javascript - Vue 路由器不渲染/挂载根路径组件
- python - 无法在 SQLAlchemy 烧瓶中设置结果对象的属性
- javascript - 如何通过单击页面打开多个 URL?
- javascript - 在 React 中检测用户是否选择了输入中的所有文本并将其删除
- git - 切换 Git Subtree 分支的正确方法?