0

In the code below, inside the inner for loop, I get the following error:

LargestProdInSeries.java:16: charAt(int) in java.lang.String cannot be applied to (java.lang.Long)

String c = numb.charAt(j);

Why should this happen when I have declared num to be a String?

Does java do an auto conversion seeing that my entire string is a number? How do I prevent this?

public class LargestProdInSeries {

    public static void main(String[] args) {

        String numb = "731671";
        Long maxProd=0L;

        for(Long i = 0L; i < numb.length() ; i++) {
            Long prod=1L;

            for(Long j=i ; j<i+3 ; j++) {
                String c = numb.charAt(j);
                prod *= Long.parseLong(c);
            }

            //inner for
            if(maxProd<prod) {
                System.out.println(maxProd);
            }
        }

        System.out.println("Max Prod = "+maxProd);

    }

}
4
  • 6
    1. charAt takes an int argument as parameter. You're passing it a Long. 2. charAt returns a char, not a String.
    – Alexis C.
    Jan 1, 2014 at 16:31
  • 1
    @ZouZou that should be the answer
    – eis
    Jan 1, 2014 at 16:35
  • Feel free to post it as an answer, i'll upvote yours =)
    – Alexis C.
    Jan 1, 2014 at 16:39
  • Great! That clears my doubt. The error is because of the parameter passed to charAt and not because of numb. Thanks! :)
    – Kaizzen
    Jan 3, 2014 at 20:47

2 Answers 2

3
for(Long j=i ; j<i+3 ; j++) {
    String c = numb.charAt(j);

as you see, you declare j to be long. String.charAt method takes int as a parameter index, and not long. To prevent this think if you really need j to be long. If you do not, change it to be int and it should work fine (I guess your String numb is not going to be longer than int's size anyway). If you do, read about converting long to integer (for example here: Convert Long into Integer).

0
String c =Character.toString(numb.charAt(j.intValue()));
1
  • @ Dejan Ciew > Even if your solution is correct, please be more explicit, and try to explain much. Next time, your answer should not been validated. Jan 1, 2014 at 22:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.