sitm sitm - 7 months ago 13
Java Question

Ho to get out of for loop at the end of the loop and enter in a new without making the sum

Here is my code. I have to count the frequency of letters in my text.
I got as output:
a 21
b 28(should be 7)
c 34(should be 6)

I think my problem is it makes the sum and i dont want it.

int[] alphabetArray = new int[26];
// char varA = 'a';
alphabetArray[0] = A;``

int count = 0;
for (int i = 0; i < text.length; i++) {
if (text[i] == A) {
count++;
}
}
System.out.println((char) alphabetArray[0] + " kommt " + count + " Mal");

alphabetArray[1] = B;

for (int i = 0; i < text.length; i++) {
if (text[i] == B) {
count++;
}
}
System.out.println((char) alphabetArray[1] + " kommt " + count + " Mal");
alphabetArray[2] = C;
for (int i = 0; i < text.length; i++) {
if (text[i] == C) {
count++;
}
}
System.out.println((char) alphabetArray[2] + " kommt " + count + " Mal");

return null;

Answer

You initialized count=0 once and you are increasing it without re-initalizing it to 0.

int[] alphabetArray = new int[26];    
// char varA = 'a';    
alphabetArray[0] = A;``

int count = 0;
for (int i = 0; i < text.length; i++) {
    if (text[i] == A) {
        count++;
    }
}
System.out.println((char) alphabetArray[0] + " kommt " + count + " Mal");

alphabetArray[1] = B;
count=0;
for (int i = 0; i < text.length; i++) {
    if (text[i] == B) {
        count++;
    }
}
System.out.println((char) alphabetArray[1] + " kommt " + count + " Mal");
alphabetArray[2] = C;
count=0;
for (int i = 0; i < text.length; i++) {
    if (text[i] == C) {
        count++;    
     }
}
System.out.println((char) alphabetArray[2] + " kommt " + count + " Mal");

return null;