Can someone help? I get the error Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 when I run this code. The error itself in the delete function. How to fix? StringBuffer and StringTokenizer are required. And also, how can you simplify the code?

 import java.util.StringTokenizer; public class main { public static int i, n; public static boolean orly = false; public static StringBuffer input, tokenStr; public static StringTokenizer out; public static char aChar; public static void main(String[] args) { input = new StringBuffer("some text"); System.out.println("Начальная строка - " + input.toString()); input = new StringBuffer(input.toString().replaceAll("[^az AZ А-Я а-я]", "")); if (input.toString().trim().length() != 0) { out = new StringTokenizer(input.toString()); System.out.println("Форматированная строка - " + input.toString()); n = (out.countTokens()); String[] charSet = { "a", "e", "o", "u", "y" }; for (i = 0; i <= n - 1; i++) { tokenStr = new StringBuffer(out.nextToken()); aChar = (tokenStr.charAt(0)); String firstchar = tokenStr.toString().substring(0,1); if (tokenStr.length() > 1) { for (int j = 0; j <= charSet.length-1; j++) { if ((!firstchar.equals(charSet[j])) || (!firstchar.toUpperCase().equals(charSet[j]))) { input.delete(input.indexOf(tokenStr.toString()),input.indexOf(tokenStr.toString())+ tokenStr.length() + 1); } } } else { input.deleteCharAt(input.indexOf(tokenStr.toString())); } } } } } 
  • Tell us which line crashes and what exactly you want to achieve with this line. - VladD
  • By the way, the result of the function indexOf may well be -1, so I would not use the value obtained in this way as an argument to the function delete without checking. - VladD pm
  • That's the problem, I don’t know how to perform this check - antoxa2584
  • The problem is that you are too lazy to break the code into functions. - dzhioev
  • You do not know how to check the value of type int , is it equal to -1 ? I would recommend a programming book. Any - VladD

1 answer 1

There are 2 potentially dangerous places in the code:

  1. String firstchar = tokenStr.toString().substring(0,1); throws an exception if the string is empty
  2. input.indexOf(tokenStr.toString()) can easily return -1, then problems cannot be avoided.

PS Notes on the calm coding:

  1. It is customary to write: for (i = 0; i < n; i++) , but not for (i = 0; i <= n - 1; i++) - it is easier to read, and the code will be a bit more optimal
  2. tokenStr.toString() I would tokenStr.toString() it as a variable
  3. In this context, StringBuilder more appropriate than StringBuffer - think about why?
  4. StringTokenizer out; I would not call the variable out , of course not the keyword , but still interferes with perception on the background of System.out
  5. Break the code into small functions - the algorithm will become clearer.