M
M
Makaron30002021-02-28 15:35:34
Java
Makaron3000, 2021-02-28 15:35:34

Why doesn't the withdrawal of attempts work as it should?

The bottom line is: To perform this task, you need to create a new variable (for example, numberOfTries), which will store the number of attempts by the user. After the successful completion of the checkGuess() method, the number of user attempts should increase by one, and after the number is guessed, it should be displayed on the screen.
But as a result, it always shows that the user guessed right on the 1st attempt, although in fact there are 2,3,5,7 of them. Tell me what's wrong?

import javax.swing.JFrame;
import java.awt.Window.Type;
import javax.swing.JLabel;

import java.awt.Dimension;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class GuesstingGame extends JFrame {
  private JTextField txtGuess;
  private JLabel lblOutput;
  private int theNumber;
  private JButton btnPlayAgain;
  
  public void checkGuess() { //Method 
    String guessText = txtGuess.getText();
    String message = "";
    int numberOfTries = 0;
    
    numberOfTries = numberOfTries + 1;
    
        
    try {//обработка ошибок, таких как ввод букв
      int guess = Integer.parseInt(guessText);
          
      if (guess < theNumber)
        message = guess + " is too low. Try again.";
      else if (guess > theNumber)
        message = guess + " is too high. Try again.";
      else {
        message = guess + " is correct. You win!.";
        message += " You win after " + numberOfTries + " tries.";
            btnPlayAgain.setVisible(true);//Who the button play again
       }
    } catch (Exception e) {//body of try-catch-finally
      message = "Enter a whole number between 1 and 100.";
    } finally {
      lblOutput.setText(message);
      txtGuess.requestFocus();
      txtGuess.selectAll();
      
      }
    
    
  
  }
  
  
  public void newGame() {  //Own method
    theNumber = (int)(Math.random() * 100 + 1);
    lblOutput.setText(""); // Скрываем текст о выигрыше
      txtGuess.setText(""); // Скрываем ввод
      btnPlayAgain.setVisible(false); // Скрываем кнопку
  }
  
  public GuesstingGame() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setTitle("Ваше имя Hi-Lo Guessting Game");
    getContentPane().setLayout(null);
    
    JLabel lblNewLabel = new JLabel("Ваше Имя Hi-Lo Guessing Game");
    lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
    lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 15));
    lblNewLabel.setBounds(0, 0, 434, 21);
    getContentPane().add(lblNewLabel);
    
    JLabel lblNewLabel_1 = new JLabel("Guess a number between 1 and 100:");
    lblNewLabel_1.setFont(new Font("Tahoma", Font.PLAIN, 12));
    lblNewLabel_1.setHorizontalAlignment(SwingConstants.RIGHT);
    lblNewLabel_1.setBounds(36, 45, 247, 21);
    getContentPane().add(lblNewLabel_1);
    
    txtGuess = new JTextField();
    txtGuess.setHorizontalAlignment(SwingConstants.RIGHT);
    txtGuess.setBounds(293, 47, 65, 19);
    getContentPane().add(txtGuess);
    txtGuess.setColumns(10);
    
    JButton btnGuess = new JButton("Guess!");
    btnGuess.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        checkGuess();
      }
    });
    
    txtGuess.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
      checkGuess();
      }
    });
    
    btnGuess.setFont(new Font("Tahoma", Font.BOLD, 13));
    btnGuess.setBounds(168, 111, 98, 36);
    getContentPane().add(btnGuess);
    
    lblOutput = new JLabel("Enter a number above and click Guess!");
    lblOutput.setFont(new Font("Tahoma", Font.PLAIN, 12));
    lblOutput.setHorizontalAlignment(SwingConstants.CENTER);
    lblOutput.setBounds(0, 171, 434, 21);
    getContentPane().add(lblOutput);
    
    btnPlayAgain = new JButton("Play Again?");
    btnPlayAgain.setVisible(false);
    btnPlayAgain.setFont(new Font("Tahoma", Font.BOLD, 11));
    btnPlayAgain.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        newGame();
        //btnPlayAgain.setVisible(false);
      }
    });
    
    btnPlayAgain.setBounds(168, 203, 98, 36);
    getContentPane().add(btnPlayAgain);
  }

  public static void main(String[] args) {
    GuesstingGame theGame = new GuesstingGame();
    
    theGame.newGame();
    
    //Ключевые слова new Dimension() в круглых скобках метода
    //setSize() сообщают компилятору Java о создании объекта типа
    //Dimension с шириной 450 пикселей и высотой 300 пикселей
    theGame.setSize(new Dimension(450, 300));
    
    //Наконец, добавьте в метод main() следующую строку, чтобы
    //приложение появилось на экране:
    theGame.setVisible(true);
    
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan., 2021-02-28
@LaRN

The numberOfTries variable is local, declared in the checkGuess() procedure, so the count starts from 0 on each attempt and previous attempts are not taken into account.
For your task, you can add a field to the GuesstingGame class that is responsible for the current number of attempts. At the start of each new game session, this field must be reset to zero, and increased during the game.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question