Compile Error: Cannot Find Symbol

后端 未结 2 1891
时光取名叫无心
时光取名叫无心 2020-12-11 22:14

I am receiving the error cannot find symbol when the code reaches the recursive call for increment and I have no idea why? Here is the code for increment. Any help will be

相关标签:
2条回答
  • 2020-12-11 22:27

    String has no method called increment. And of course it isn't a recursive call because you are inside an object(which object? in your code there isn't a class definition) , meanwhile you are invoking increment upon a String object.

    In addition your temp field is never used. If you want to share it between method calls you can try something like this:

    public void increment (String temp){}
    

    and then pass it while calling it:

    String temp = new String(num.substring(0, num.length()-2));
    increment(temp);
    

    Of course your function can't work like that. temp parameter should be managed inside your increment method. Review your logic. It's no more a matter of syntax. If you can't change the method signature then declare temp as a field of your BigNatural class:

    public class BigNatural {
    
    private String num; 
    private String temp
    ......
    

    and inside increment method simply do:

    temp = new String(num.substring(0, num.length()-2));
    
    0 讨论(0)
  • 2020-12-11 22:27

    Some other pointers:

    String is an immutable class meaning once it is created it can no longer be changed. So, doing

    String t = new String();
    t = last.toString();
    

    has now sense since you will create 2 String Objects here (last.toString() will create and return a new String).

    Simply do:

    String t = last.toString();
    

    or even better:

    num.concat(last.toString());
    

    Same goes for temp String, simply do:

    String temp = num.substring(0, num.length()-2);
    

    Next, be aware of unintentional autoboxing:

    Integer first = 0;
    first++;
    

    this will create a new Integer Object every time first++ is executed; Integer (as String) is immutable. When calculating simply use the primitive int instead of Integer.

    Finally, be careful that you don't create an infinite loop. If I understand your code num will concatenated to so num.length() > 1 will be true always if it was true the first time.

    0 讨论(0)
提交回复
热议问题