I had the exact same issue. Your Java version in capacitor.build.gradle file is version 17. I downloaded jbr-17.0.12 from within the Android Studio. Then make sure your $JAVA_HOME, Java path in Android studio and (very important) in android/gradle.properties file all point to the same location for jbr.
Especially check the org.gradle.java.home value in android/gradle.properties. In my case, it was set to Android Studio java version. I changed it to jbr17 and project started compiling successfully.
#org.gradle.java.home=/Applications/Android Studio.app/Contents/jbr/Contents/Home org.gradle.java.home=/Users/xyz/Library/Java/JavaVirtualMachines/jbr-17.0.12/Contents/Home