我在猜數字程序,我在循環中遇到問題。當我運行程序並在文本框中輸入一個數字,然後按回車就會凍結。我發現這可能是由於無限循環而發生的。如果我錯了,隨時糾正我。基本上,當我在文本框中輸入一個數字並按下輸入時,它假設改變一個標籤並更改背景顏色,但這不會發生,我認爲它是因爲我的循環運行,直到win變成true,當我鍵入我的號碼時,它一直運行這個數字而不是輸出正確的標籤,讓我輸入一個不同的數字到文本字段中。 P.S:我知道newGame按鈕不起作用猜數字遊戲的圖形用戶界面 - 無限循環
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class GuessingGame implements ActionListener
{
JFrame guessFrame;
JPanel guessPanel;
JTextField guessText;
JButton newGame;
JLabel rangeLbl, enterGuessLbl, winLbl;
Random rand = new Random();
int numToGuess = rand.nextInt(1000)+1;
int numOfTries = 0;
int guess;
public GuessingGame()
{
// Create the frame and container.
guessFrame = new JFrame("Guess the Number");
guessPanel = new JPanel();
guessPanel.setLayout(new GridLayout(5,0));
// Add the widgets.
addWidgets();
// Add the panel to the frame.
guessFrame.getContentPane().add(guessPanel, BorderLayout.CENTER);
// Exit when the window is closed.
guessFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Show the converter.
guessFrame.pack();
guessFrame.setVisible(true);
}
// Create and add the widgets for converter.
private void addWidgets()
{
// Create widgets.
guessText = new JTextField();
guessText.setHorizontalAlignment(JTextField.CENTER);
rangeLbl = new JLabel("I have a number between 1 and 1000. Can you guess my number?", SwingConstants.LEFT);
enterGuessLbl = new JLabel("Please enter your guess", SwingConstants.LEFT);
winLbl = new JLabel(" ", SwingConstants.CENTER);
newGame = new JButton("New Game");
// Listen to events from Convert textfield.
guessText.addActionListener(this);
// Add widgets to container.
guessPanel.add(rangeLbl);
guessPanel.add(enterGuessLbl);
guessPanel.add(guessText);
guessPanel.add(winLbl);
guessPanel.add(newGame);
}
// Implementation of ActionListener interface.
public void actionPerformed(ActionEvent event)
{
boolean win = false;
guess = Integer.parseInt(guessText.getText());
if (guess == numToGuess)
{
win = true;
}
else if (guess < numToGuess)
{
winLbl.setText("Too Low");
guessPanel.setBackground(Color.red);
guess = Integer.parseInt(guessText.getText());
}
else if (guess > numToGuess)
{
winLbl.setText("Too High");
guessPanel.setBackground(Color.blue);
guess = Integer.parseInt(guessText.getText());
}
winLbl.setText("Correct!");
guessPanel.setBackground(Color.green);
}
public static void main(String[] args)
{
GuessingGame game = new GuessingGame();
}
}
我認爲我是理解也許我只是編輯了問題發佈完整的代碼 – TubaShark
刪除while循環建議,你不需要它在這裏。 – Marcinek
我刪除了while循環,現在我輸入的任何數字都是正確的哈哈 – TubaShark