java - 嵌套for循环,不拾取数组中的第一个实例
问题描述
我正在尝试对一个单词进行编码,但我不确定为什么我的 for 循环没有选择第一个实例 0。此方法的输入是“This”和 3。此方法的输出是 klv。所以我的循环一定不能正常工作,因为字母 T 被跳过了。我的循环有什么问题?
String encodeWord(String word, int Shift) {
//word = "This"
//Shift = 3, is how far the letter is shifted to the right of the original
char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
char[] temp = word.toCharArray();
char[] FA = new char[temp.length];
String tempWord = "";
StringBuilder sb = new StringBuilder(64);
for (int x = 0; x < word.length(); x++) {
for (int y = 0; y < alphabet.length; y++) {
if (word.charAt(0) == alphabet[y]) {
FA[0] = alphabet[y + shift];
System.out.println(FA[0]);
}
}
}
for (int i = 0; i < word.length(); i++) {
for (int j = 0; j < alphabet.length; j++) {
if (word.charAt(i) == alphabet[j]) {
FA[i] = alphabet[j + shift];
sb.append(FA[i]);
System.out.println(FA[i]);
}
}
}
System.out.println(sb);
return sb.toString();
}
解决方案
字母“T”与字母“t”不同,因此由于您的数组中仅找到字母“t”,程序将找不到字母“T”的匹配项。
您的代码的另一个问题是,如果输入包含字母“x”、“y”或“z”,您将得到一个 Index out of bounds 异常,因为在数组中它们后面没有 3 个字母。
推荐阅读
- python-3.x - 访问不同屏幕的属性
- node.js - Axios Azure 函数 POST 在 NODEJS 中抛出错误
- reactjs - Redux 身份验证不使用更新的道具?
- ios - 为什么在尝试访问 iTunes 资料库时出现错误?
- partitioning - AWS Glue 使用输出存储桶中的文件写入和压缩
- html - 这个带有 `%button` 的代码笔中的 HTML 代码是什么?
- c# - 找不到 ASP.Net Core 应用程序部件视图
- scala - Spark 无法爆炸列
- jenkins - 如何在 jenkins groovy 中使用 fmt_case?
- node.js - 在 nodejs 服务器上处理套接字连接和 http 请求