-3

The following code generates this error message and I'm not exactly sure why: "non-static variable charArray cannot be referenced from a static context." The code is here:

import java.util.*;

public class MyClass{

    String userInput;
    char[] charArray;

    public static void main(String args[]){
        MyClass testString = new MyClass("hello"); 
        for(int i = 0; i < charArray.length; i++){

        }
    }

    MyClass(String input){
        userInput = input; 
        charArray = input.toCharArray(); 
    }
}

Any suggestions on how to fix this?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
aejhyun
  • 612
  • 1
  • 6
  • 19
  • In `for(int i = 0; i < charArray.length(); i++){` which `charArray` you want to access? – Pshemo Aug 02 '15 at 17:07
  • http://stackoverflow.com/questions/2559527/non-static-variable-cannot-be-referenced-from-a-static-context – Mick Mnemonic Aug 02 '15 at 17:08
  • 1
    Your edit changed your question into one with other problem. Such edits are not allowed since they make posted answers or duplicate links invalid. If you have new problem post new question, but only after you searched for solution earlier (that is why there is minimum time limit which needs to pass before you being able to ask new question). – Pshemo Aug 02 '15 at 17:12

1 Answers1

2

Change

for(int i = 0; i < charArray.length(); i++){

to

for(int i = 0; i < testString.charArray.length; i++){

charArray is an instance member of the MyClass class, so it requires an instance of that class in order to be accessed. testString holds a reference to an instance of that class, and can be used to access charArray.

Eran
  • 387,369
  • 54
  • 702
  • 768