JO_VIC JO_VIC - 3 months ago 35
Java Question

Using for loop and charAt to check if each letter appears exactly twice in a word

i'm writing a program in java that checks if a letter appers exactly twice, i was able to write it but my problem is that for some words the code doesn't check if the letter appear exactly twice.
here is my code:

public class Test {

public static void main(String[] args) {
isDoubloon("abba");
isDoubloon("Shanghaiingss");/*it still prints out true though 's' does appear exactly twice*/}


//checks if every letter appears twice in a word
public static void isDoubloon(String s){
String l=s.toLowerCase();
int count=0;

for(int i= 0; i<l.length()-1;i++){
for(int j=i+1;j<l.length();j++){

if(l.charAt(i)==l.charAt(j)) count++;
}

}
if(count%2==0){
System.out.println("True, This is a doubloon");
}else
System.err.println("False, This is not a doubloon");


}}

Answer

Your whole logic is not correct. You have to check for every letter in your text if it occurs twice.

Try this:

String l=s.toLowerCase();
boolean check = true;

for(int i= 0; i<l.length();i++){
    int count=0;
    for(int j=0;j<l.length();j++){
        if(l.charAt(i)==l.charAt(j)) count++;
     }
     if (count != 2) {
         check = false;
         break;
     }
}
if(check==true){
    System.out.println("True, This is a doubloon");
}else
    System.out.println("False, This is not a doubloon");
}