所以这是我代码的一部分。如果我为preTranslation字符串输入“1111”,它应该打印出true,但它打印出false。我猜测.equal()无法比较这两个值,但我不知道另一种方式。有什么帮助吗?
import javax.swing.JOptionPane;
import java.util.Arrays;
public class test3
{
public static void main ( String [] args )
{
String s1 = "Morse";
// Decide whether Morse code or English
String decide = JOptionPane.showInputDialog("Enter 'English' for Morse to English code translation and 'Morse' for English to Morse code translation. Pay attention to Caps.");
// Enter String & decide whether to convert to Morse or English
String preTranslation = JOptionPane.showInputDialog("Enter the words you wish to translate.");
if ( decide.equals( s1 ))
toMorse( preTranslation );
else
toEnglish( preTranslation );
}
// Translate to Morse
public static void toMorse( String preTrans )
{
// Initialize english letters
char[] english = new char[3];
// Initialize english numbers
english[0] = 1;
english[1] = 2;
english[2] = 3;
// Initialize morse characters
String[] morse = {".","-", ".-"};
// Replace spaces with |
String phraseWithDelimiter = preTrans.replace( " ", "|");
String[] translation = new String[phraseWithDelimiter.length()];
System.out.println( phraseWithDelimiter.substring(0, 1).equals( english[0] )); // Should print out to be true
}
}
答案 0 :(得分:2)
您正在将String对象与字符(char)进行比较,因此equals将始终返回false。如果要从字符串中获取单个字符,请使用charAt方法而不是substring。
答案 1 :(得分:0)
使用 String.valueOf(phraseWithDelimiter.substring(0,1))。equals(english [0]));
答案 2 :(得分:0)
使用charAt
更正字符比较:
phraseWithDelimiter.charAt(0) == english[0]
您定义:
english[0] = 1;
是ASCII 1,用户无法输入的字符。您需要定义:
english[0] = '1';
答案 3 :(得分:0)
只是详细说明JamesB的答案,如果你看一下String类的equals方法的实现:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
您会注意到,如果您要比较的对象不是String的实例(在您的示例中是字符),则会立即返回false。 :)