Java字符串comparsion [英] Java string comparsion
问题描述
我想实现一个简单的密码塞萨尔。我在与codeS基于一个新的关键[]字符串函数的麻烦。在这里我表示,我怎么设置我的钥匙。
I'm trying to implement a simple cesar cipher. I'm having trouble with the function that codes a string based on a new key[]. Here I shown, how I setup my key.
private String[] alphabet = {"a", "b", "c","d", "e", "f","g", "h", "i","j", "k", "l","m", "n", "o",
"p", "q", "r","s", "t", "u","v", "w", "x","u", "z"};
public String[] CoderNewKey(int shift) {
_NewKey = null;
_NewKey = new String[25];
for (int i = 0; i < 25; i++) {
_NewKey[i] = alphabet[(i + shift) % 25];
}
return _NewKey;
}
我的问题是codeR,没有任何的if语句是永远正确的,rtnstring始终只是。
The problem I have is with Coder, none of the if statements are ever true, and rtnstring is always just "".
public String Coder(String[] key, String msg){
String rtnstring = "";
for ( int i = 0; i < msg.length();i++){
for (int x = 0; x<26 ; x++){
if ( msg.substring(i, i+1) == alphabet[x]){
rtnstring.concat(key[x]);
}if (msg.substring(i, i+1) == " "){
rtnstring.concat(" ");
}
}
}
return rtnstring;
}
下面是我为codeR方法的逻辑。
Here is my logic for the coder method.
它经历一次的弦乐味精1个字母。它匹配其字母表中的索引信,然后创建基于该指数在给定的密钥一个新的字符串。
It goes through the String msg 1 letter at a time. It matches the letter with its index in the alphabet, then it creates a new string based on the index's in the given key.
推荐答案
您需要使用的 等于()
从String类的方法。当您使用 ==
你比较两个对象的引用变量(这是不是在你的code相同)
You need to use equals()
method from the String class. When you use ==
you are comparing the reference variable of two objects (which is not same in your code)
+----------+ +----------+
| | What you need | |
| " " <-------to compare-----------> "a" |
| | | |
| | | |
+----------+ +----------+
^ ^
| |
+ What you +
rtnstring <------+ erroneously +----> msg
compare
这篇关于Java字符串comparsion的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!