简体   繁体   English

java自动将字符串转换为long?

[英]java auto converts string to long?

In the code below, inside the inner for loop, I get the following error: 在下面的代码中,在内部for循环内,出现以下错误:

LargestProdInSeries.java:16: charAt(int) in java.lang.String cannot be applied to (java.lang.Long) LargestProdInSeries.java:16:java.lang.String中的charAt(int)无法应用于(java.lang.Long)

String c = numb.charAt(j);

Why should this happen when I have declared num to be a String? 当我将num声明为String时,为什么会发生这种情况?

Does java do an auto conversion seeing that my entire string is a number? Java是否可以看到我的整个字符串都是数字来进行自动转换? 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. 如您所见,您声明j为long。 String.charAt method takes int as a parameter index, and not long. String.charAt方法将int作为参数索引,并且不长。 To prevent this think if you really need j to be long. 为了防止这种情况,请考虑是否真的需要j长。 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). 如果不这样做,请将其更改为int,它应该可以正常工作(我想您的String numb不会比int的大小长)。 If you do, read about converting long to integer (for example here: Convert Long into Integer ). 如果这样做,请阅读有关将long转换为整数的信息(例如,在此处: 将Long转换为Integer )。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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