Where is the error in my code?

Go To StackoverFlow.com

-2

/** 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; 
}
2012-04-04 05:12
by Lulu Larson
What kind of error are you getting - Mike Samuel 2012-04-04 05:14
Can you write a little introduction about what you are trying to do maybe... and what error you get - dann.dev 2012-04-04 05:14
also remove ==true from your condition - Adil Soomro 2012-04-04 05:15
I don't know. Where is the error in your code? (A stack trace might answer that question. - Louis Wasserman 2012-04-04 05:18
Sorry everyone, I'm not too sure. I'm a newbie to Java. @Adil Soomro, why would I remove ==true - Lulu Larson 2012-04-04 05:22
@LuluLarson: Actually it was not an error, I suggested you for the optimization of your code. Becasue isPrime() will return you boolean, since you can directly call if(true) or if(false), then no need to double comparison - Adil Soomro 2012-04-04 05:27
@AdilSoomro, it's not an optimization. I'm pretty confident either the compiler or the JIT can remove the == true. It's good advice, but to benefit human readers - Matthew Flaschen 2012-04-04 05:28


4

It should be:

s = s + c;

You want to concatenate the character if it's prime.

2012-04-04 05:14
by Matthew Flaschen


0

Maybe you want to write

s = s + c

Then do you want evaluate isPrime on char ASCII code or on char position? That is do you want 'A' value is 65 (the ASCII code) or 1 (because A is the 1 letter)? In the first case fix

s = s + c

it is enough, but in second you need change also

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

and do not pass "c" but

if (Loops.isPrime( (int)c - (int)'A' + 1 )==true) {
2012-04-04 05:25
by dash1e
Sorry for not clarifying. I wanted it in the ASCII code. Thank you for the extra info - Lulu Larson 2012-04-04 05:30
Ads