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())); } } } } }
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 pmint
, is it equal to-1
? I would recommend a programming book. Any - VladD