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)
"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 errorString index out of range: 6- Sanek Zhitnik