-11

代码第一次正常运行,然后使用 while 循环再次运行,假设我第一次输入 AA,它变成 CC,然后它再次运行我再次输入 AA,它会出现 CCCC 再次执行它会出现 CCCCCC我不希望每次循环时都不需要它来保留字符串中的数据。

import java.util.*;
public class SecretCypher {

    public static void main(String args[]) {

        Scanner kb = new Scanner(System.in);
        StringBuffer e = new StringBuffer();
        System.out.println("Welcome to Secret Cypher!");

            char loop = 'Y';
            while(loop == 'Y' || loop == 'y') {
                System.out.println("");
                System.out.println("Enter your cypher in upper case.");
                String s = kb.nextLine();


                char[] cs = s.toCharArray();
                for (int i = 0; i < cs.length; i++) {
                    e.append((char)('A' + (cs[i] - 'A' + 2) % 26));
                }
                if(s == s.toLowerCase()) {
                    System.out.println("Remember to use upper case letters!");
                    System.exit(0);//Also I was bored of using break and this works any where in the code.
                }
                System.out.println(e.toString());


                System.out.println("Do you want to enter another cypher? > ");
                String again = kb.nextLine();
                if(again.charAt(0) == 'N') {
                    System.out.println("Hope you come back again!");
                    break;
                }
            }
    }
}
4

1 回答 1

3

您正在重用相同的字符串缓冲区。如果你一直把东西放入同一个缓冲区而不清除它,你显然会从以前的迭代中得到无关的东西。

只需在 while 循环内声明 StringBuffer ,以便在每次迭代时创建它。

无论如何,你应该学会使用你的调试器,而不是在这里要求我们调试。如果有的话,使用调试器可以为您在这里遇到的麻烦提供非常有价值的洞察力。

于 2013-08-15T15:02:47.490 回答