How can I compare a char to a string or sequence of chars? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

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) "

10th May 2018, 10:37 AM
Ilie Razvan
Ilie Razvan - avatar
1 Answer
0
error is clear "string index out of range" in the first for loop for(j=0; j<n; j++) j should be less than n and not equal to n as n is the length, so index of last enement is n-1
10th May 2018, 10:47 AM
‎ ‏‏‎Anonymous Guy