gpt4 book ai didi

java - 是什么导致我的java代码的这部分出现空指针异常?

转载 作者:行者123 更新时间:2023-12-01 17:38:31 25 4
gpt4 key购买 nike

我需要创建一个按钮数组,每个按钮都有自己的 Card,来自另一个程序(我在其中称为 Deck)。实例化卡片,然后实例化按钮后,我不断收到空指针异常,我不知道它来自哪里。如果您不明白我在说什么,请随时询问;我对编程还比较陌生。

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

public class TenCard extends JFrame implements ActionListener
{
// a window with borders, title bar, buttons and panel.
private static JFrame f;

// panel that will hold the contents
private JPanel p;

// declare deck and displayed cards
private Deck myDeck; //Deck
private Card[] playerCards1;
private Card[] playerCards2;


/**********components**********/

//JButtons
private JButton[] cardbuttons1;
private JButton[] cardbuttons2;
private JButton sortbutton;
private JButton shufflebutton;
private JButton flipbutton;


//Textfields
private JTextField text1;
private JTextField text2;


//Menu
private JMenuBar menuBar;
private JMenuItem item1, item2;
/*****ending the components*****/

/**
* constructor that instatiates
* the frame, panel, layout, etc and
* adds two cards to the panel
*/
public TenCard()
{
f = new JFrame("High Card Game");

// create the content panel
p = new JPanel();

// set the layout
GridLayout layout = new GridLayout(2,3);

// instantiate game and assign cards
myDeck = new Deck();
myDeck.shuffle();


Card playerCards1[]= new Card[5];
for (int i=0; i<5; i++)
{
playerCards1[i]= myDeck.dealOneCard();
}


Card playerCards2[]= new Card[5];
for (int i=0; i<5; i++)
{
playerCards2[i]= myDeck.dealOneCard();
}





// set layout
p.setLayout(layout);
addCardsToPanel();
addFieldToContentPanel();

// add the content to the window
f.setContentPane(p);
}

/**
* Create and add three buttons to content panel
*/
public void addCardsToPanel()
{
// instantiate buttons with images
sortbutton = new JButton("sort cards");
shufflebutton = new JButton("shuffle cards");
flipbutton = new JButton("flip cards");


JButton cardbuttons1[] = new JButton[5];
for (int i = 0; i < 5; i++)
{
cardbuttons1[i] = new JButton("player 1, card" +i, playerCards1[i].getBackImage());

}

JButton cardbuttons2[] = new JButton[5];
for (int i = 0; i < 5; i++)
{
cardbuttons2[i] = new JButton("player 2, card" +i, playerCards2[i].getBackImage());
}


// add buttons

p.add(sortbutton);
p.add(shufflebutton);
p.add(flipbutton);


}

最佳答案

private Card[]      playerCards1;
private Card[] playerCards2;

这两个变量永远不会初始化,因此会出现 NullPointerException。在 public TenCard() {} 中,您重新声明具有相同名称的变量,因此只有局部变量被初始化

Card playerCards1[]= new Card[5];   // --> Remove this line to work with the "outside" playerCards1
for (int i=0; i<5; i++)
{
playerCards1[i]= myDeck.dealOneCard();
}

对playerCards2做同样的事情

关于java - 是什么导致我的java代码的这部分出现空指针异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61004137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com