Search code examples
javastatic-methodsnon-static

How to solve "Cannot Make Static Reference to Non-Static Method" in a Java mastermind game?


This question is based on my former question. How to add a "cheat" function to a Java mastermind game I added the cheat function to my program, but it cannot compile because of "Cannot Make Static Reference to Non-Static Method"(the old codes works, you can check it through the link I post). Here are my new codes:

import java.util.*;

public class mm {
  static int[] random;
  public static void main(String[] args) {
    System.out.println("I'm thinking of a 4 digit code.");

    //update
    mm m1 = new mm();
    random = m1.numberGenerator();

    int exact=0, close=0;
    while(exact!=4){
      int[] guess= m1.userinput(); //update
      exact=0;
      close=0;
      for(int i=0;i<guess.length;i++){
        if(guess[i]==random[i]){
        exact++;
        }
        else if (random[i]==guess[0] || random[i]==guess[1] || random[i]==guess[2] || random[i]==guess[3]) {
                    close++;
        }
      }
      if(exact==4){
        System.out.println("YOU GOT IT!");
      }
      else{
        System.out.println("Exact: "+exact+" Close: "+close);
      }
    }   
  }

  public int[] userinput() {
    System.out.print("Your guess: ");
    Scanner user = new Scanner(System.in);
    String input = user.nextLine();
    //cheater
    if (input.equals("*")) {
      System.out.format("Cheater!Secret code is:");
      for(int i=0;i<random.length;i++){
        System.out.print(random[i]);
      }
    }
    int[] guess = new int[4];
    for (int i = 0; i < 4; i++) {
      guess[i] = Integer.parseInt(String.valueOf(input.charAt(i)));
    }
    return guess;
  }

  public int[] numberGenerator() {
    Random rnd = new Random();
    int[] randArray = {10,10,10,10};
    for(int i=0;i<randArray.length;i++){
      int temp = rnd.nextInt(9);
      while(temp == randArray[0] || temp == randArray[1] || temp == randArray[2] || temp == randArray[3]){
        temp=rnd.nextInt(9);
      }
      randArray[i]=temp;
    }
    return randArray;
  }
}

How to solve this?


Solution

  • You can't call a non-static method directly from a static method. in public static main(String [] args) To do so, you should first create an object of the class.

    try this at main method:

    mm m1 = new mm();
    random = m1.numberGenerator();
    
    int [] guess = m1.userInput();
    

    this should work