java - 错误地使用for循环

标签 java string loops for-loop

在下面的代码中,for 循环永远不会被执行。我尝试通过断点和监视来解决问题。返回密文的正确长度,但是 for 循环直到 int i >= ciphertext.length() 才会递增。事实上,除了“调试”消息之外,似乎没有任何内容执行。

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 开始并转到 length -1 )。

当你遇到困难时,总是用纸和铅笔大声地描绘出你的循环,这总是有帮助的。

关于java - 错误地使用for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14573489/

相关文章:

java - 将 DecimalFormat 与 ThreadLocal 结合使用会对性能产生哪些影响?

java - Eclipse包名以com开头

c# - C# 上价格/现金/货币的文本框

c - 向用户读入字符串,直到使用 "."

Java字符串: Checking for consecutive letters or numbers

java - 使用java套接字编程查询文件传输

java - 当数字超过 100 时如何解决 jlabel 数字问题?

javascript - 使用 JavaScript 在 SharePoint 库中创建文件夹结构

c++ - C++ 的嵌套循环

php foreach 循环与数组