import java.util.Scanner; public class Main { public static void main(String[] args) { int length = 1; String output = null; Scanner sc = new Scanner(System.in); System.out.print("Введите текст: "); String word = sc.nextLine(); for(int i = 0; i < word.length(); i++){ if (word.charAt(i) == word.charAt(i + 1)){ length=+1; } if (word.charAt(i) != word.charAt(i + 1)){ output = String.valueOf(+ word.charAt(i)); if (length > 1){ output = String.valueOf(+length); } } } System.out.print(output); } } 

Tell me what to fix in this code.

Task: Jaaaavvvva = Ja (4) v (4) a

errors:

 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6 at java.lang.String.charAt(String.java:658) at Main.main(Main.java:14) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) 
  • You have the string "Hello" . The elements of this line are numbered from zero, hence the latter will have an index of 4. The length of line 5. You check that the value of the iterator is less than the length, and then compare two adjacent ones. Well, the last element is tested for the length of the string, but when you try to access an element with an index one more, you get the error String index out of range: 6 - Sanek Zhitnik
  • @SanekZhitnik as for me, the author knows about this principle, he just did not foresee everything - dirkgntly

2 answers 2

Logs always talk about the exception thrown, so I advise you to familiarize yourself with the primitive exceptions.

Here it is the source of the word.charAt(i+1) error.

When i reaches the last character, we will request the element the последний элемент + 1 , but there is no such element, therefore an exception is thrown. Therefore, it needs to be thought out, at least by the condition i+1<length

In this example:

 Scanner sc = new Scanner(System.in); System.out.print("Введите текст: "); String word = sc.nextLine(); String output = ""; for(int i = 0, length = 1; i < word.length(); i++) { if (i + 1<word.length() && word.charAt(i) == word.charAt(i + 1) ){ length++; } else { output+=word.charAt(i); if(length>1) output+=length; length = 1; } } System.out.println(word + " = " + output); 

Conclusion:

 Jaaaavvvva = Ja(4)v(4)a 

    Your code is just awful. For you wrote using Scanner.

     Scanner scan = new Scanner(System.in); //СЛУШАЕМ ВАС byte[] bytes = scan.nextLine().getBytes(); // int i = 0; int max = bytes.length; ByteArrayOutputStream buffer = new ByteArrayOutputStream(max); // создаем буфер, первоначальный размер буфера = max // ДЛЯ СЧИТАВОДА БУКВ byte t = 0; // прошлый байт int c = 0; // количество байт одинаковых VVV = 3 // byte a = 0; //для неделанья новой ссылки на обьект, хранит текущий байт while(i<max){ //ОСНОВА a = bytes[i]; i = i + 1; // if(t == a){ // прошлый байт равен текущему, ага +1 c = c + 1; continue; } // то что не равно if(c>0){ buffer.write(40); // ( buffer.write(String.valueOf(c + 1).getBytes()); // вывести количество совпадений buffer.write(41); c = 0; // в количество одинаковых что-то осталось, стереть! } t = a; //записываем текущий в буфер для будующих сравнений buffer.write(a); } System.out.println(buffer.toString());//ЗАПИСЫВАЕМ В ПОТОК ВЫВОДА buffer.reset(); // если используем повторно функцию то чистим буфер 
    • The better your code? What is a, b, c, t, i? What is buffer.write (40)? - Mikhail Kuchma
    • The code is practically working, inserted and it works. buffer.write (40); // (. I even noted that 40 is a symbol (according to the ASCSII table. The better it is, the fact that it is three hundred times faster than your code, it is easy to translate it into any other programming language, it is easy to understand the interpreter and therefore different types of optimization or translation of some designs in machine code - Denis Kotlyarov