Skip to content
Advertisement

Char Append in String at Run Time Error Variable might not have been initialized

For Example I’m having an error if want to printout the cipher String after end of for loop:

System.out.print("Cipher Text IS : >>> ");
for (int i = 0; i < len; i++)
{
    char a = plainText.charAt(i);
    for (int j = 0; j < allChar.length(); j++)
    {
        if (allChar.charAt(j) == a)
        {
            char c = allChar.charAt(j + key);
            String cipher = "null" + c;

            System.out.print("t" + c);
        }
        System.out.println(cipher);
    }
}

Advertisement

Answer

You need to change this (see my comments inline):

for(int j=0; j<allChar.length(); j++)
{
    if(allChar.charAt(j) == a)                   
    {
        char c= allChar.charAt(j+key);
        String cipher = "null"+c;

        System.out.print("t"+c );
    }
    System.out.println(cipher);
    // cipher is not defined / initialzed here.
    // this is not the "end" of the loop but within its body,
    // thus prints on every iteration
}

to:

cipher  = ""; // initalize cipher
for(int j = 0; j < allChar.length(); j++)
{
    if(allChar.charAt(j) == a)                   
    {
        char c= allChar.charAt(j + key);
        cipher += "null"+c; // don't know the logic here!

        System.out.print("t" + c);
    }
}
System.out.println(cipher); // print result after loop
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement