1

I'm currently working on a text editor. I have an entire GUI working, and now I'm trying to add usability to it.

For some reason, when I try to create an array called symbols, NetBeans is fine with it -- when I try to assign a value to the array, NetBeans won't compile my program, and will instead give an error and suggest it make a new class for the array.

Example code:

String[] symbols = new String[42]; symbols[0] = "∑"; // Error line!

Here's an image: http://img401.imageshack.us/img401/4844/examplegx.png

Does anyone know the solution to fix this or has this happened to you? If I need to provide more detail, let me know.

2 Answers 2

8

You're trying to put an arbitrary statement directly in your class declaration, instead of in a method, constructor or initializer block. You can't do that.

Some options:

  • Do it in the constructor:

    public GUI()
    {
        symbols[0] = "∑";
    }
    
  • Do it in an initializer block:

    String[] symbols = new String[42]; 
    {
        symbols[0] = "∑";
    }
    
  • Do it in a method called by the initializer:

    String[] symbols = getDefaultSymbols();
    
    private static String[] getDefaultSymbols()
    {
        String[] ret = new String[42];
        ret[0] = "∑";
        return ret;
    }
    
  • Use an array initializer:

    String[] symbols = { "∑", null, null, null, ... };
    

Note that your question is phrased as if Netbeans were to blame. It's not Netbeans - it's the Java language rules. Your code wouldn't be valid under Eclipse, javac, IntelliJ etc.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for the help, this code worked for my program.
This is a good example as it shows the use of a function call to initialize a value, few people know this is possible.
3

You cannot place code outside a method or initializer block. What you can do is;

String[] symbols = new String[42]; { symbols[0] = "∑"; }

You can also define your symbols this way

String[] symbols = "∑,+,-,/,*,^".split(",");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.