-3

The lexical analyzer must accept a string with the same number of a and b.

The program accepts any chain that has a and b.

public static int i;

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
 Scanner input = new Scanner(System.in);
    String s;


    System.out.println("Input something to lexically analyze:  ");
    s = input.next( );
    int j = 0;

     if(s.charAt(i)=='a'||'b'){
      for (int i = 1; i < s.length(); i++) {  

            j++;

            if(i==j){
            System.out.println("cadena correcta");
            }
        }

     }
     else {
        System.out.println("cadena incorrecta\n");
        System.exit(0);
    }
 }

}

I am trying to count how many times a and b is repeated to know if you have the same number of letters but it has not worked for me.

Andronicus
  • 25,419
  • 17
  • 47
  • 88
  • It will be hard to help with the logic when the program doesn't even compile. You have multiple errors for `if(s.charAt(i)=='a'||'b'){`, at that point `i` isn't defined, did you mean `j`? Also, you can not compare against two characters like that, you need to do `if(s.charAt(j)=='a'||s.charAt(j)=='b'){` – Roger Lindsjö Aug 09 '19 at 05:06

1 Answers1

0

The following code counts the number of as and bs in a string. It should guide you in the right direction.

String str = "aaabbabb";
int aCount = str.length() - str.replace("a", "").length();
int bCount = str.length() - str.replace("b", "").length();
System.out.println(aCount == bCount); // true
Avi
  • 2,611
  • 1
  • 14
  • 26