-3

We have a school project where we are creating a text-based Black Jack game. I have created different classes like BlackJackDeck, Card, Hand, Player, and Dealer. My Teacher wants us to have a class called BlackJack were the game logic will be. I tried to make a main method inside BlackJack and added a reference to shuffle my BlackJackDeck deck. But it says that "non-static variable length leken cannot be referenced from a static context". If I don't have a main method my program won't be able to run. Here is my code:

package blackjack;
import java.util.ArrayList;

/**
 * @version 1.0
 * @author robert.englund
 */
public class BlackJack {

ArrayList<Spelare> spelare = new ArrayList<>(); //List with players
BlackJackKortlek leken = new BlackJackKortlek(4); //BlackJackDeck
Dealer dealer = new Dealer(); //The dealer

public static void main(String[] args) {

    leken.blanda(); //Shuffle deck

}


}

How should I do it so that I can make the game runnable so that I can write the game logic? Thanks in advance!

j08691
  • 204,283
  • 31
  • 260
  • 272
robeng
  • 85
  • 2
  • 10

4 Answers4

0

You should instantiate BlackJackKortlek leken = new BlackJackKortlek(4);

insinde of your main() method. After you have done that you can call the methods.

mrkernelpanic
  • 4,268
  • 4
  • 28
  • 52
0

You can't access a non-static variable from a static context. Your variables(non-static) are outside of main method(static).
Declare your variables as below:

static ArrayList<Spelare> spelare = new ArrayList<>();
static BlackJackKortlek leken = new BlackJackKortlek(4);
static Dealer dealer = new Dealer();

Or declare it inside main:

public static void main(String[] args) {
    ArrayList<Spelare> spelare = new ArrayList<>(); //List with players
    BlackJackKortlek leken = new BlackJackKortlek(4); //BlackJackDeck
    Dealer dealer = new Dealer();
}
KL_
  • 1,503
  • 1
  • 8
  • 13
0

you could simply declare leken as a static variable.

private static BlackJackKortlek leken = new BlackJackKortlek(4); 

Also you should read on what the static keyword actually means.

Bentaye
  • 9,403
  • 5
  • 32
  • 45
0

You are trying to access non-static variable leken inside a static method which you should not do, the reason being instance variables comes under picture only when you create the Object where as static method can be accessed without creating the object.

public static void main(String[] args) {
   leken.blanda(); // leken is non-static variable.
}

So, create the object inside the main method.

public static void main(String[] args) {
       BlackJackKortlek leken = new BlackJackKortlek(4); //BlackJackDeck
       leken.blanda(); // leken is non-static variable.
    }
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62