# Test Question(Introduction Course)

• November 19th, 2012, 09:44 PM
Daler
Test Question(Introduction Course)
Hey guys,

Here is the question: Design Java code to find and return the frequency of string b in string a.

For example , if string a = "abcdabcfabxyabd" and string b = "ab"
The frequency should be equal to 4

Here is my code:

Code :

```import java.util.*; public class StringFrequency_A_in_B { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String s1, s2; String commonChars = ""; int lengthCommon = 0;   System.out.println("The program will find the characters " + "quantity/frequancy \nof the first string in the second string"); System.out.println("Now, enter two strings in seperate lines");   s1 = scan.nextLine(); s2 = scan.nextLine();   int len = s1.length(); // number of characters in string A   for (int i = 1; i < len ; i++) { char ch = s1.charAt(i); if (s2.indexOf(ch) != -1) { commonChars = commonChars + ch; } } // end of the loop   lengthCommon = commonChars.length();   System.out.println("The common characters: " + commonChars); System.out.println("The frequency of common characters: ” + lengthCommon);   System.exit(0); } }```

The thing is that it doesn't count the frequency of "ab", but the quantity of a's and b's, so it shows 8. How do I make it count frequency of "ab" string?
• November 19th, 2012, 10:22 PM
curmudgeon
Re: Test Question(Introduction Course)
Don't look for common chars since char is not what you're interested in. Instead search for Strings within a String.
• November 19th, 2012, 10:51 PM
Daler
Re: Test Question(Introduction Course)
So I should use String instead of chars, right??

--- Update ---

I have changed my code and it shows the right answer, but the output shows like a few Errors before the answer:

Error
Error
Error
Error
Error
Error
4

Code :

```import java.util.*; public class FrequencyAinB { public static void main (String [] args) { Scanner scan = new Scanner(System.in); String a,b; int freq = 0; int pos; a = "abcdabcfabxyabd"; b = "ab";   int lenA = a.length() - 1;   while(lenA>0) { lenA--; pos = a.indexOf(b); if(pos == -1) { System.out.println("Error"); } else { a = a.substring (pos + 1); freq++; } } System.out.println(freq); } }```

What's wrong with logic?
• November 19th, 2012, 11:10 PM
curmudgeon
Re: Test Question(Introduction Course)
You're while loop looks quite a bit strange. Why are you dealing with a length variable, lenA? What's the point of that? Why are you creating a substring of the a String? Why not use one of the overrides of the indexOf method that takes a second parameter?