我创建了一个丹麦游戏,您应该猜测1-10的数字。
当我输入一个数字来检查我的猜测是否正确时,我在控制台中收到错误。
当我输入一个号码并检查号码是否正确时,我有什么想法可以解决问题?
Game.java
import java.util.Random;
public class Game {
int randomNumber;
public Game() {
// Set randomNumber to randon number [1;10]
Random rand = new Random();
randomNumber = rand.nextInt(10) + 1;
}
public int getRandomNumber() {
return randomNumber;
}
}
GameFrame.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GameFrame extends JFrame implements ActionListener{
private Game game;
private Player player;
private JTextField inputField;
private JLabel gameAnswer, tries;
public GameFrame(String title) {
super(title);
getContentPane().setLayout(new FlowLayout());
setSize(300, 100);
// Start game & add player
game = new Game();
player = new Player();
addComponents();
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void addComponents() {
JLabel tries = new JLabel("Forsøg: " + player.getTries());
getContentPane().add(tries);
inputField = new JTextField(8);
getContentPane().add(inputField);
JButton submitGuess = new JButton("Gæt tal");
submitGuess.addActionListener(this);
getContentPane().add(submitGuess);
JLabel gameAnswer = new JLabel("Gæt et tal mellem 1-10");
getContentPane().add(gameAnswer);
}
private void resetGame() {
// Create new randon number & new player
game = new Game();
player = new Player();
// Set default text in components
gameAnswer.setText("Gæt et tal mellem 1-10");
tries.setText("Forsøg: " + player.getTries());
}
@Override
public void actionPerformed(ActionEvent e) {
// Increment tries guessed
player.addTry();
tries.setText("Forsøg: " + player.getTries());
// Extract number guessed
String textEntered = inputField.getText();
int numberEntered = Integer.parseInt(textEntered);
// How was it compared to randomNumber?
if (numberEntered == game.getRandomNumber()) {
// CORRECT! - display optionpane
JOptionPane.showMessageDialog(null, "TILLYKKE! Du gættede rigtigt! Du brugte: " + player.getTries() + " forsøg.");
// Reset Game
resetGame();
} else if (numberEntered > game.getRandomNumber())
// To high
gameAnswer.setText("Forket! Du gættede for højt!");
else if (numberEntered < game.getRandomNumber())
// To low
gameAnswer.setText("Forkert! Du gættede for lavt!");
// Calculate result & display
}
}
Main.java
public class Main {
public static void main(String[] args) {
new GameFrame("Gæt et tal");
}
}
Player.java
public class Player {
private int tries;
public Player() {
tries = 0;
}
public void addTry() {
tries++;
}
public int getTries() {
return tries;
}
}
答案 0 :(得分:1)
您将private JLabel gameAnswer, tries;
声明为类字段但从未对其进行初始化,因为在addComponents()
方法中,您使用以下命令声明并初始化新对象:
JLabel tries = new JLabel("Forsøg: " + player.getTries());
JLabel gameAnswer = new JLabel("Gæt et tal mellem 1-10");
所以你得到NullPointerException
。你需要声明它:
tries = new JLabel("Forsøg: " + player.getTries());
gameAnswer = new JLabel("Gæt et tal mellem 1-10");
它应该有用。