Java 不正确地使用for循环
在下面的代码中,永远不会执行for循环。我尝试用断点和手表来解决这个问题。返回密码文本的正确长度,但是for循环直到int i>=ciphertext.length时才会增加。事实上,似乎没有任何东西会在“调试”消息之后执行Java 不正确地使用for循环,java,string,loops,for-loop,Java,String,Loops,For Loop,在下面的代码中,永远不会执行for循环。我尝试用断点和手表来解决这个问题。返回密码文本的正确长度,但是for循环直到int i>=ciphertext.length时才会增加。事实上,似乎没有任何东西会在“调试”消息之后执行 private void decrypt_btnActionPerformed(java.awt.event.ActionEvent evt) { String alphab
private void decrypt_btnActionPerformed(java.awt.event.ActionEvent evt) {
String alphabet= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
String ciphertext="fRcXFBxXTRJ";
status_label.setText( "Decryption has begun" );
JOptionPane.showMessageDialog(null,"ciphertext-length: " + ciphertext.length() + "\n" + ciphertext,"Debug", JOptionPane.INFORMATION_MESSAGE);
for (int i = 0; i>=ciphertext.length(); i--){
System.out.println("inc:" + i);
String cipher_current_char = getLetterAtIndex(ciphertext, i);
int pos_char_in_alphabet = getIndexAtLetter(alphabet, cipher_current_char);
if(pos_char_in_alphabet-2<0){
plain_ta.setText(getLetterAtIndex(alphabet, (alphabet.length()+(pos_char_in_alphabet -2)+1 ) ));
status_label.setText( 100/i + "%");
}else{
cipher_current_char = getLetterAtIndex(ciphertext, i);
pos_char_in_alphabet = getIndexAtLetter(alphabet, cipher_current_char);
plain_ta.setText(getLetterAtIndex(alphabet, (pos_char_in_alphabet-2)));
status_label.setText( 100/i + "%");
}
}
}
你需要改变条件,否则逻辑就错了
for (int i = ciphertext.length()-1; i>=0; i--){
你需要反向工作。还要注意-1,您需要它来避免越界异常。索引从0开始,到长度-1
当你陷入困境时,总是用纸和铅笔大声地画出你的循环,这总是有帮助的
i>=ciphertext.length()
应该是
i < ciphertext.length()
首先,我强烈建议您学习如何使用IDE的调试器。您还应该学习如何为调试目的向代码添加System.out.println调用 话虽如此,让我们看看for循环:
for (int i = 0; i>=ciphertext.length(); i--)
假设您已经到达for循环,密文的长度为10。i被初始化为零。然后检查条件是否大于或等于10。不,它不是,所以整个for循环被跳过
请注意,for循环的条件必须为true,循环才能继续。它不用于告诉for循环何时停止
因此,我们可以解决此问题:
for (int i = 0; i<=ciphertext.length(); i--)
现在我从0增加到10。然而,当我10岁时,你会得到一个例外。这是因为唯一有效的索引是从0到9。最后一个修复将改变问题:
for (int i = 0; i<ciphertext.length(); i++)
学习使用调试器。:-在if语句上设置一个断点并在它被命中时检查它的值可以解释您遇到的问题。不应该,检查是在实际执行循环的其余部分并递减之前进行的。如:i>=0吗?是的,执行循环体,减量i,再次检查,等等,是的,我忘了。。你只差一步;长度是一过终点。
for (int i = 0; i<=ciphertext.length(); i++)
for (int i = 0; i<ciphertext.length(); i++)