Search code examples
javahelperpolish

Why is my code giving me an out of range exception?


I have such a program:

import java.util.Scanner; import java.io.*;

class C { public static void main (String[] args) throws IOException{

    System.out.println("Wpisz teks do zakodowania: ");

    String tekst;
        Scanner odczyt = new Scanner(System.in);
        tekst = odczyt.nextLine();
        System.out.println("Tekst odszyfrowany:" + tekst);
        char[]alfabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
        int dlugalf=26;
        System.out.print("Tekst zaszyfrowany:");

        int a = 0;

        for(int i=0;;){

            System.out.print(tekst.charAt(a));
            a++;

        }
    }   
}

After its launch, you should view the question and ask you to enter text. Then it should show the sign that I wrote, and the program must load each of these letters individually, not as a whole string. But then it pops up an error:

Exception in thread "main" java.lang.StringIndexOut OfBoundsException: String index out of range: 10
at java.lang.String.charAt(Unknown Source)
at C.main(C.java:34)

It is caused by an empty string. How can I get rid of it? I tried with this command:

if (!tekst.isEmpty() && tekst.charAt(0) == 'R');

but it did not work out.

Sorry for any mistakes; I do not speak English very well.


Solution

  • This block of code:

    int a=0;
    for(int i=0;;){
    
      System.out.print(tekst.charAt(a));
      a++;
    }
    

    Should become

    for(int a=0;a<tekst.length();a++){
         System.out.print(tekst.charAt(a));
    }
    

    As it is, your loop will try to go forever. You run out of characters in the String (when a=tekst.length()) and you get the exception.