我的代码中的错误在哪里?

时间:2012-04-04 05:12:34

标签: java

/** Yields: a String that contains each capital Letter (in 'A'..'Z') whose representation is prime */

public static String primeChars() {
    String s = "";

    // inv: s contains each capital in "A'..c-1 whose representation is prime

    for (char c = 'A'; c <= 'Z'; c=(char)(c+1)) {
        if (Loops.isPrime((int)c) == true) {
            s= s+1;
        }
    }

    // s contains each capital in 'A' ..'Z' whose rep is a prime

    return s; 
}

2 个答案:

答案 0 :(得分:4)

应该是:

s = s + c;

如果字符是素数,你想连接字符。

答案 1 :(得分:0)

也许你想写

s = s + c

那么你想要在char ASCII代码或char位置上评估isPrime吗? 那你想要'A'值是65(ASCII码)还是1(因为A是1个字母)? 在第一种情况下修复

s = s + c

这已经足够了,但是第二个你也需要改变

if (Loops.isPrime((int)c)==true) {

并且不要传递“c”但是

if (Loops.isPrime( (int)c - (int)'A' + 1 )==true) {