-4

I am studying Java as a beginner, but I did not understand this script.

I have a 'look and say' assignement.
Can anyone tell me how this is working?

public class App {

  public static void main(String[] args) {

    for (int k = 0, len = args.length; k < len; k++) {

      int i, j;


      StringBuilder preNumber = new StringBuilder("1");     // what is the use of StringBuilder?
      StringBuilder AnsNumber = new StringBuilder();

      int n = Integer.parseInt(args[k]);

      for (i = 1; i <= n; i++) {

        AnsNumber = preNumber;
        int l = preNumber.length(), cnt = 1;
        StringBuilder nxtNumber = new StringBuilder();

        for (j = 1; j < l; j++) {

          char ch = preNumber.charAt(j);

          if (preNumber.charAt(j - 1) == preNumber.charAt(j))   // what does charAt(j) means?
          {
            cnt++;
          } 
          else 
          {
            nxtNumber.append(cnt);
            //why '+' isnot using as concatination?

            nxtNumber.append(preNumber.charAt(j - 1));
            cnt = 1;
          }

          // System.out.println(nxtNumber);
        }

        nxtNumber.append(cnt);
        nxtNumber.append(preNumber.charAt(j - 1));
        preNumber = nxtNumber;
      }
      System.out.println(AnsNumber);
    }
  }
}
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64

1 Answers1

1

You can easily get your answers if you look at the Java Doc.

  • StringBuilder class is used to create mutable strings. It performs way better than normal String class (which is immutable). Reason here: What is difference between mutable and immutable String in java
  • charAt(j) returns the character at the j'th index within the string (indexing is 0 based).
  • '+' is used to concat String objects. append() is used to concat StringBuilder objects (add some String to the end of the StringBuilder object).
iavanish
  • 509
  • 3
  • 8