gpt4 book ai didi

java - 运算符 == 不能应用于 java.lang.String char

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:43:45 24 4
gpt4 key购买 nike

我在 NetBeans Java 应用程序中没有遇到任何错误,但在将代码应用到 Android Java 项目时确实遇到了上述错误。我尝试了 if (alpha[i].equals(c)) { 但是我不会像在 NetBeans 中那样得到任何结果,NetBeans 将字符串转换为摩尔斯电码,例如SOS... --- ...

NetBeans Java 应用程序(有效,当我键入 SOS 时我得到... --- ...):

private static String toMorse(String text) {
char[] characters = text.toUpperCase().toCharArray();
StringBuilder morseString = new StringBuilder();
for (char c : characters) {
for (int i = 0; i < alpha.length; i++) {
if (alpha[i] == c) {
morseString.append(morse[i] + " ");
break;
}
}
}
return morseString.toString();
}

Android Java 项目(不起作用,当我输入字符串时,我什么也得不到):

public String toMorse(String text) {
char[] characters = text.toUpperCase().toCharArray();
StringBuilder morseString = new StringBuilder();
for (char c : characters) {
for (int i = 0; i < alpha.length; i++) {
if (alpha[i] == c) { // error is on this line
morseString.append(morse[i] + " ");
break;
}
}
}
return morseString.toString();
}

奇怪的是,这部分代码在 NetBeans 和 Android Studio 中都有效(当我输入 ... --- ... 我得到 SOS):

public String toEnglish(String text) {
String[] strings = text.split(" ");
StringBuilder translated = new StringBuilder();
for (String s : strings) {
for (int i = 0; i < morse.length; i++) {
if (morse[i].equals(s)) {
translated.append(alpha[i]);
break;
}
}
}
return translated.toString();
}

阿尔法和莫尔斯数组:

private String[] alpha = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8",
"9", "0", " "};

private String[] morse = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.",
"--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-",
"-.--", "--..", ".----", "..---", "...--", "....-", ".....",
"-....", "--...", "---..", "----.", "-----", "|"};

最佳答案

问题是 alpha 是一个 String 数组,而 c 是一个字符。您正在比较 (char == string) ,这显然不像预期的那样工作。

关于java - 运算符 == 不能应用于 java.lang.String char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30134254/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com