0

It seems to be a very common question relating with arrays and comparing in java, however I couldn't find the right answer in all of these for my case.

In this application I am trying to make a program which 'encrypts' text given by the user. For example: user gives characters 'a b c' and the program returns it as '@ # $'. But as you may notice I am having some issues in the code "pozita[i] = j;". Why won't this code work? It doesn't give me an error? Or is there anyway of doing it as "new pozita[i]" or anything like that?

Well, I'd be glad if someone could help me through. I am stuck for a while. Thanks in advance! :)

import java.util.*;
import javax.swing.*;
import java.awt.*;

public class TestPerProgram extends JFrame
{
    char[] alfabeti = {'a','b','c','r','n','t'};
    char[] kodimi = {'@','#','%','*','^','$'};
    int[] pozita;
    //Scanner merr = new Scanner(System.in);

    String fn = JOptionPane.showInputDialog("Jepe tekstin:");
    char[] input = fn.toCharArray();

    void numro()
    {
        for (int i=0; i<=input.length; i++)
        {
            for(int j=0; j<=input.length; j++)
            {
                if(alfabeti[j] == input[i])
                {
                    pozita[i] = j;
                    System.out.println(pozita[i]);
                }
            }
        }

        /*
        for (int k=0; k<=input.length; k++)
        {
            System.out.println(pozita[k]);
        }
        */

    }

    public static void main(String[] args)
    {
        TestPerProgram pjesa = new TestPerProgram();

        pjesa.numro();

    }

}
  • 3
    *It doesn't give me an error?* Yes, it does. Read it. Then read http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it – JB Nizet Oct 14 '14 at 22:04

3 Answers3

1

I'm not 100% clear on how your algorithm is supposed to work, but it seems you may want to replace the line

pozita[i] = j;

with

pozita[i] = kodimi[j];

Right now, you are only writing the matching index to pozita, not a replacement character.

If my assumption is correct, you would also change

int[] pozita;

to

char[] pozita;

and initialize it to an array of length input.Length.

Eric J.
  • 147,927
  • 63
  • 340
  • 553
1

You never instantiated the array pozita. After you instantiate pozita, you can then start overriding the values in pozita. You are assigning j to posita[i] , posita is null.

Do something like:

int posita[] = new int[20]

and if you don't want to set size then just use an arraylist.

kolonel
  • 1,412
  • 2
  • 16
  • 33
0

You have not requested memory to be allocated for your variable pozita or otherwise instantiated it. The way you are currently using it, you would write pozita[] = new int[input.length]; at some point after retrieving your input from the user.

abiessu
  • 1,907
  • 1
  • 18
  • 16