The task is as follows:

  1. Count the number of words per line

  2. Remove all "a" characters from a string

  3. Remove every third character from the string

Code solves 2 conditions. This is the maximum I have reached, but the program curses.
How to implement the third item?

public static void main(String[] args) { /*1*/ Scanner in = new Scanner(System.in); String a = in.nextLine(); int c = a.split(" ").length; System.out.println("слов в строке : " + c); /*2*/ String b = a.replaceAll("a", ""); System.out.println("cтрока без a : " + b); /*3*/ int i = 3; int j; StringBuffer sb = new StringBuffer(a); int d = a.split("").length; System.out.println(d); d = d + 1; while (i <= d) { StringBuffer g = sb.deleteCharAt(i); System.out.println(g); i = i + 3; } } 
  • "the program swears" - this is something vague and very far from the scientific. This is not a kindergarten. If an exception occurs while the program is running, this is the way to talk and apply stacktrace with an indication of exactly which line of error occurs. Even " StringIndexOutOfBoundsException in the StringBuffer g=sb.deleteCharAt(i); string StringBuffer g=sb.deleteCharAt(i); " was already useful and would show that you are serious about this. - Regent
  • I wouldn’t fix my code, but I would like to know from users how you can solve the 3rd condition. Forgive me, of course. - Marat Zimnurov

1 answer 1

The problem is that you delete characters, going from the beginning of the line and at the same time applying indices (3, 6, 9, etc.) and the length of the original line to the already changed one, for which the length decreases with each iteration (which leads to the exception), and the character indexes to be deleted are different.

You can either take into account the length of the variable sb and use the appropriate indices:

 for (int i = 2; i < sb.length(); i += 2) { sb = sb.deleteCharAt(i); } System.out.println(sb); 

Or go to the end of the line:

 StringBuffer sb = new StringBuffer(a); int i = a.length() - a.length() % 3 - 1; for (; i > 0; i -= 3) { sb = sb.deleteCharAt(i); } System.out.println(sb); 

In both cases, the result for the source line 1234567890 is 1245780 , and for 123456 , the result is 1245 .

The length of the string can be obtained using the .length() method - there is no need to split the string into an array of characters.

  • Thank you!) I understood everything!) - Marat Zimnurov