0

Possible Duplicate:
How do I compare strings in Java?

I have an array of Strings, the array is called Morse:

private final static String[] Morse = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....",
    "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-",  ".-.", "...", "-", "..-",
    "...-" ,".--" ,"-..-", "-.--", "--..",".-.-.-","--..--","..--.." ,"|"};

private final static String[] Colours = {"red","green","white"};

Then there is my code:

char[] stringArray;
stringArray = converttoMorse(letter).toCharArray();

char ch;

for(int i=0;i<stringArray.length;++i)
{
    if(stringArray[i]== "." ) //Problem here
    {
        System.out.println(Colours[0]);
    }
    else if (stringArray[i] == "-" ) //Problem here
    {
        System.out.println(Colours[1]);
    }
    else
    {
        System.out.println(Colours[2]);
    }
}

This is only a snippet of my actual program, the english to morse is working absolutely perfect. HOWEVER, I would like to indicate the dots and dashes as colors "red" and "green" respectively as string (with spaces indicating white).

I used the toCharArray() method to breakdown the printed outcome Morse as an array. However I'm not able to correspond each of these dots and dashes to their specific colours. For example, I would like ".-" to show as "red green". How can I do this? Is there a specific method for doing so?

4

3 回答 3

4

因为stringArray是 achar[]您需要将其内容与 a 进行比较char

你需要:

if (stringArray[i] == '.') 
// '.' is the dot character,
// "." is a String that contains only the dot character 

如果你想比较字符串,你应该阅读这个问题:How do I compare strings in Java?

于 2013-01-27T21:48:03.987 回答
0

在我看来,您有 a String[],并且您希望结果是 aString[]以指示红绿色。为此,我们将使用一些正则表达式和外部方法。我什至不想弄乱 char 数组,因为从那个到 String 数组会不那么简单。

注意:这假定您的数组中没有元素是null,否则肯定会爆炸。您可以在 之前进行简单的空检查replaceAll以减轻这种情况。

public static String[] convertToRedGreen() {
    // Since the array we want is static, our method is too.
    String[] redGreen = new String[Morse.length];
    for(int i = 0; i < Morse.length; i++) {
        redGreen[i] = Morse[i].replaceAll("[.]", " red ").replaceAll("[-]", " green ");
    }
    return redGreen;
}

这会给你一个String[]看起来像这样的东西。

[ red  green ,  green  red  red  red ,  green  red  green  red ,  green  red  red ,  red ,  red  red  green  red ,  green  green  red ,  red  red  red  red ,  red  red ,  red  green  green  green ,  green  red  green ,  red  green  red  red ,  green  green ,  green  red ,  green  green  green ,  red  green  green  red ,  green  green  red  green ,  red  green  red ,  red  red  red ,  green ,  red  red  green ,  red  red  red  green ,  red  green  green ,  green  red  red  green ,  green  red  green  green ,  green  green  red  red ,  red  green  red  green  red  green ,  green  green  red  red  green  green ,  red  red  green  green  red  red , |]
于 2013-01-27T22:04:18.693 回答
-1

Don't use == to compare strings: see here

于 2013-01-27T21:20:57.670 回答