Kaizzen
Kaizzen

Reputation: 5

java auto converts string to long?

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);

    }

}

Upvotes: 0

Views: 370

Answers (2)

Dejan Ciev
Dejan Ciev

Reputation: 142

String c =Character.toString(numb.charAt(j.intValue()));

Upvotes: 0

3yakuya
3yakuya

Reputation: 2662

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).

Upvotes: 3

Related Questions