0

Can you explain this code?

import java.util.Scanner; public class NLengthStringFromKLength { public void print(int n, char[] k, char[] A) { if (n <= 0) { System.out.print(String.valueOf(A) + " "); } else { for (int i = 0; i < k.length; i++) { A[n - 1] = k[i]; print(n - 1, k, A); } } } public static void main(String[] args) { Scanner in=new Scanner (System.in); String k=in.next(); int n=in.nextInt(); NLengthStringFromKLength i = new NLengthStringFromKLength(); i.print(n, k.toCharArray(), new char[n]); } }

24th Dec 2018, 11:12 AM
Hoda
4 Answers
0
The aim of program is to print all the possible N length string from a input string. For example, if you entered "ABCD" and provided N="2", then the output will be all the possible strings of length 2 that is, "AB","BC","CD","CA".... if N was 3, then output will be "ABC","BCD","CDA","ACB","BCA"... This code is available on internet too, if you want more explanation https://algorithms.tutorialhorizon.com/all-n-length-strings-from-given-string-of-length-k/
24th Dec 2018, 12:00 PM
Mayank Dhillon
Mayank Dhillon - avatar
0
😄 Thank you so much but the problem is that I don't get those statements: 1) public void print(int n, char[] k, char[] A) 2)NLengthStringFromKLength i = new NLengthStringFromKLength(); 3)i.print(n, k.toCharArray(), new char[n]); } Can you please explain them, I'm a learner and this code seems very confusing 😅
24th Dec 2018, 12:08 PM
Hoda
0
I would suggest you to complete this Java course first because the code is pretty straightforward and nothing too complex was used in it. https://www.sololearn.com/Course/Java/ If you have anything specific that you have doubt in I will surely help you out. And about statements you asked, I will try my best to explain those to you. 1) public void print(int n, char[] k, char[] A) What we have done is that we have defined a method named print which takes an integer n, and two strings k and A which are array of characters as input. 2)NLengthStringFromKLength i = new NLengthStringFromKLength(); by this line we have declare a new instance of class NLengthStringFromKLength class. Now "i" being an instance of the class can access all the methods of the class. Now say if you wanted to use the print method of the class which I explained earlier then you will have to write NLengthStringFromKLength .print(parameters) which is not convenient, but by creating "i" as the instance of the class you can use same method as i.print() which is much easier to type. 3)i.print(n, k.toCharArray(), new char[n]); In this statement we have passed the parameter to print method of class NLengthStringFromKLength which are integer and two arrays of char type. Now, since k was of type string, so to convert it required data type which is char we use .tochar().
24th Dec 2018, 3:39 PM
Mayank Dhillon
Mayank Dhillon - avatar
0
Thank you for explaining themđŸ˜â€ I understand now.
24th Dec 2018, 4:17 PM
Hoda