-1

I'm creating a program that is supposed to create a memorization game that assigns colors to a user, and then tests how well the user can relay the colors back. Because of this, I created an array class that has two arrays (one with colors already assigned to numbers, and another that uses the first array to randomly assign colors for the game's purpose).

Because of this, I then need to access the array class from the main in order to extract which colors were actually chosen -- and this is where I'm running into problems, specifically when I try to create an instance of the colorArrays class. Here is the code for my main class:

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

public class Mission13Main
{

   public static void main (String[] args) // This is the main driver of the program
   {               

  //Start of game: 
  //--------------------------------------------------------
  colorArrays color = new colorArrays();//"error: non-static variable this cannot be referenced from a static context"

  System.out.println(color.getColor(0));//A test to see if I can use getColor

  JOptionPane.showMessageDialog(null, "How good is your memory?\nTry to memorize this color sequence:\n \n" + color.getColor[0] + " " + color.getColor[1] + " " + color.getColor[2] + " " + color.getColor[3] + " " + color.getColor[4] + " " + color.getColor[5] + " " + color.getColor[6] + " ");                            

   }  

I had some of these command lines commented out so that I could get the program to compile.

Here's the arrayColors class:

//Class to construct arrays and assign colors to user
//-----------------------------------------------------------   
public class colorArrays
{     
  String[] getColor
  String[] userColor;   
  colorArrays color;      

  public void colorArrays() //Array Constructor
  {

     Random   r = new Random();            
     String test = "test";  


     //Array # 1 for the colors user may get
     //------------------------      

     String[] color = new String[10];

     color[0] = "red";
     color[1] = "yellow";      
     color[2] = "blue";
     color[3] = "green";      
     color[4] = "purple";
     color[5] = "brown";
     color[6] = "black";      
     color[7] = "white";
     color[8] = "pink";
     color[9] = "orange";


     //Array # 2 which selects the colors user will memorize
     //-------------------------      

     String[] userColor = new String[7];                              

     for (int i = 0; i <= 6; i++)
     {
        int randomC = r.nextInt(10);
        userColor[i] = color[randomC];
        System.out.print(userColor[i] + " "); //--> a test to see if it is assigning colors properly      
     }
     //--------------------------------------------------------------         

  }
     //Method to extract specific color
     public String getColor (int n)
     {                                
        String correctColor = "";
        correctColor = color.userColor[n];
        return correctColor;

     }                                    
}

I've spent a long time on this program, and feel that I'm fairly close, but that gathering information from the other classes is really slowing me down. I feel like all the classes work individually, but I just can't get them to communicate properly. Any help is greatly appreciated.

UPDATE:

Here is the full code as everyone else suggested.

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

public class Mission13Main
{

   public static void main (String[] args) // This is the main driver of the program
   {               

      //Start of game: 
      //--------------------------------------------------------
      colorArrays color = new colorArrays();//"error: non-static variable this cannot be referenced from a static context"

      System.out.println(color.getColor(0));//A test to see if I can use getColor

      JOptionPane.showMessageDialog(null, "How good is your memory?\nTry to memorize this color sequence:\n \n" + color.getColor[0] + " " + color.getColor[1] + " " + color.getColor[2] + " " + color.getColor[3] + " " + color.getColor[4] + " " + color.getColor[5] + " " + color.getColor[6] + " ");                            

   }            

   //-----------------------------------------------------------
   // Class that is the code for the game
   //-----------------------------------------------------------
   public class MemoryGame
   {

      private JFrame mainWindow;   
      private JLabel color1;
      private JLabel color2;
      private JLabel color3;
      private JLabel color4;
      private JLabel color5;
      private JLabel color6;
      private JLabel color7;
      private JLabel gameResults;     
      private JTextField txtColor;      

   //-------------------------------------------------------------
      public MemoryGame () // This is the constructor for the class -- creates an instance of the class
      {

         //creating frame             
         mainWindow = new JFrame();   
         mainWindow.setSize(600,400);
         mainWindow.setTitle("Memory Game");
         mainWindow.setDefaultCloseOperation(mainWindow.EXIT_ON_CLOSE);
         mainWindow.setLayout(new FlowLayout());

         //building contents
         color1 = new JLabel("Enter color # 1: ");                        
         color2 = new JLabel("Enter color # 2: ");
         color3 = new JLabel("Enter color # 3: ");
         color4 = new JLabel("Enter color # 4: ");
         color5 = new JLabel("Enter color # 5: ");
         color6 = new JLabel("Enter color # 6: ");
         color7 = new JLabel("Enter color # 7: ");

         txtColor = new JTextField(15);

         //Add contents
         mainWindow.add(color1);
         mainWindow.add(txtColor);                                  
         mainWindow.add(gameResults); 

         //add action listener      
         txtColor.addActionListener(new CheckListener()); 

      } //end of create contents



      // Action Listener:
      //--------------------------------------------------------------------
      private class CheckListener implements ActionListener
      {
         public void actionPerformed(ActionEvent e)
         {                              
            Mission13Main m = new Mission13Main();  

            int i = 0;

            if (i == 0)
            {
               gameResults.setText("Correct Guess");
            }
            else
            {
               gameResults.setText("Incorrect Guess.");
            }        
         }
      }
   }   
   //Class to construct arrays and assign colors to user
   //-----------------------------------------------------------   
   public class colorArrays
   {     
         String[] getColor;
         String[] userColor;   
         colorArrays color;      

      public colorArrays() //Array Constructor
      {

         Random   r = new Random();            
         String test = "test";  


         //Array # 1 for the colors user may get
         //------------------------      

         String[] color = new String[10];

         color[0] = "red";
         color[1] = "yellow";      
         color[2] = "blue";
         color[3] = "green";      
         color[4] = "purple";
         color[5] = "brown";
         color[6] = "black";      
         color[7] = "white";
         color[8] = "pink";
         color[9] = "orange";


         //Array # 2 which selects the colors user will memorize
         //-------------------------      

         String[] userColor = new String[7];                              

         for (int i = 0; i <= 6; i++)
         {
            int randomC = r.nextInt(10);
            userColor[i] = color[randomC];
            System.out.print(userColor[i] + " "); //--> a test to see if it is assigning colors properly      
         }
         //--------------------------------------------------------------         

      }
         //Method to extract specific color
         public String getColor (int n)
         {                                
            String correctColor = "";
            correctColor = color.userColor[n];
            return correctColor;

         }                                    
   }
}  

I'm sorry if it's indented weird, I'm new to this and not sure how to easily format it.

Thank you for everyone who is being NICE about my question -- I feel like while many users are very helpful and supply constructive criticism, others may be condescending about beginners not knowing as much as them. I only started learning about object oriented programming last week -- today finally figuring out what the constructor is actually used for. -- so thank you for the kind responses.

Kody_06
  • 163
  • 2
  • 9
  • 3
    `public void colorArrays() //Array Constructor` - no, that's not a constructor, it's a method called `colorArrays` with a return type of `void`. – Jon Skeet Jun 24 '16 at 00:01
  • Constructors don't have a return type; remove the `void` at the very least. – Dave Newton Jun 24 '16 at 00:01
  • 1
    I suspect your `colorArrays` class is also a nested class - if that's the case, make it a top-level type. – Jon Skeet Jun 24 '16 at 00:04
  • Unrelated, but the `getColor` method sets the return value to an empty string, then sets it to something else, then returns it--it might be cleaner to just have a one-liner: `return color.userColor[n];` Except this also doesn't make any sense; `color` is a string, which does not have a `userColor` method; perhaps you meant something else? – Dave Newton Jun 24 '16 at 00:04
  • You don't show where the member "colorArrays" is defined in your Mission13Main class. The error suggests that you have made it an instance field which cannot be used like that in a static context. Try declaring the colorArrays field as static. – Andrew Tavera Jun 24 '16 at 00:08
  • If you have a problem or a question with/about the behaviour of users, then please ask this on [meta]. The main page (http://stackoverflow.com) is for programming related questions and we should stick to that. – Tom Jun 24 '16 at 00:23
  • I updated the question with the complete code. I've gotten downvoted because apparently this has already been answered, but the answer on the other one is not helping me figure it out. I've read multiple threads on stack exchange about accessing a non-static class from the static main method, but the answers are not answering why mine won't work. – Kody_06 Jun 24 '16 at 00:45
  • @user6374022 You can't construct non-static nested classes without an instance of the outer class. Just declare `colorArrays` as static and it'll work. – shmosel Jun 24 '16 at 19:48

1 Answers1

0

1st. You need to read on naming convention. Class names should start with capital letter.

2nd.

public void colorArrays() { //Array Constructor

This is wrong... constructors can not be void as they do not have any return type. You need to change this to:

public colorArrays() {

3rd. Your code is badly indented :)

4th. Ok so now it all makes sense. You are trying to instantiate an inner class from a static method by the looks of it.

In your main method you need to do

colorArrays color = new Mission13Main().new colorArrays();  

to instantiate an inner class from static main method.

Static methods belong to a specific class instead of specific instance of the class. If you are trying to instantiate a method (non static) from within static method, the software does not know (at the time of a start up) what this is - unless you create an instance of this class and then refer to the method.

Also you should put class in its own 'file' - unless you specifically need inner class but i can not see this necessary in your example. By doing so it will make your code more readable and easier to maintain and in general nicer :)

Maciej Cygan
  • 5,351
  • 5
  • 38
  • 72
  • 1
    Valid points, but neither answers the question. – shmosel Jun 24 '16 at 00:03
  • 1
    "Neither" of the 3? But the comment about 'public void' certainly does answer the question, yes? – Lew Bloch Jun 24 '16 at 00:08
  • @shmosel well his code does not produce what he is saying it is for a start. if you change the return type on constructor the code compiles - it does throw null pointer at one point but it still compiles. – Maciej Cygan Jun 24 '16 at 00:17
  • Removing "void" does not fix the problem. When trying to construct an instance of the class, I still get the "error: non-static variable this cannot be referenced from a static context" – Kody_06 Jun 24 '16 at 00:22
  • @LewBloch There were only 2 when I wrote the comment. Having a `void` method with the same name as the class is not illegal, though it does generate a warning. OP's error is likely caused by trying to instantiate a non-static nested class from a static method, as Jon Skeet pointed out. – shmosel Jun 24 '16 at 00:22
  • @shmosel well according to what OP has provided us i can not reproduce the error reported. Possibly Jon is right - but again without full code not much we can do. – Maciej Cygan Jun 24 '16 at 00:24
  • I updated the question with the complete code. I've gotten downvoted because apparently this has already been answered, but the answer on the other one is not helping me figure it out. I've read multiple threads on stack exchange about accessing a non-static class from the static main method, but the answers are not answering why mine won't work. – Kody_06 Jun 24 '16 at 00:46