简体   繁体   中英

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

    }

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM