How can I compare a char to a string or sequence of chars?
import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner cin = new Scanner(System.in); String s1 = cin.nextLine(); int n = s1.length(); int j; int k = 0; int i =0; char[] s = new char[n]; for (j = 0; j <= n; j++) { if (s1.charAt(j) == '@!#$%^') { if (j - 1 < 0) break; s[i] = s1.charAt(j - 1); i++; k++; } } for(i=0;i<=k;i++) System.out.println(s[i]); cin.close();} } // with only one char ('@') the program have no errors but when I run it : "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2 at java.base/java.lang.StringLatin1.charAt(Unknown Source) at java.base/java.lang.String.charAt(Unknown Source) at sololearn.RemoveChars.main(RemoveChars.java:18) "