试图从JTextfield获取输入并在另一种方法中使用

时间:2012-04-30 06:42:42

标签: java swing

我遇到了尝试存储位于GuessGame()方法中的JTextfield的值并将它们放入findMiddleNumber()中的数组的问题。程序结束时我得到的只是用户的最后一个输入,即randomNumber。

有人可以看看我的代码,看看我错在哪里

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

public class GuessGame extends JFrame
{
Container container;
int currentDistance;

int inputGuess;
int lastDistance;
int medianValue = 40;
int middleNumber;
int positionIndex = 5;

private JButton newGame;
private JLabel message;
private JLabel prompt; 
private JLabel numberInput;
private JTextField guessInput;
private int countGuess;
private int randomNumber;



public GuessGame()
{
    super( "Play Guess A Number Game Version 2.1" );
    setLayout( new FlowLayout() );

    countGuess = 0;

    prompt = new JLabel( "A random number between N and 100 has been"
            + " selected." );
    numberInput = new JLabel( "Write your number and press enter key: ");

    guessInput = new JTextField( 5 );
    guessInput.addActionListener( new GuessHandler() );
    message = new JLabel( "The result will be shown here." );


    newGame = new JButton( "Start New Game" );
    newGame.addActionListener( new ActionListener()
    {
        @Override
        public void actionPerformed( ActionEvent event )
        {

            guessInput.setText("");
            guessInput.setEditable(true);

            generateNumber();

        }
    });

    container = getContentPane();
    container.add( prompt);
    container.add( numberInput );
    container.add( guessInput );
    container.add( message );
    container.add( newGame );

    setSize( 380, 150 );
    setVisible( true );

    generateNumber();

}

private void generateNumber()
{
    randomNumber = ( int ) ( Math.random() * 93 + 7 );
    System.out.println( randomNumber );

}        

public void processGuessedNumber( int usersGuess )
{
    countGuess++;

    if ( countGuess == 1 )
    {
        lastDistance = Math.abs( usersGuess - randomNumber );

        if ( usersGuess > randomNumber )
            message.setText( "Higher than correst guess." );
        else
            message.setText( "Lower than correct guess." );

    }

    else 
    {
        currentDistance = Math.abs( usersGuess - randomNumber );

        if ( usersGuess > randomNumber )
        {
            message.setText( "Higher than correct guess." );

            lastDistance = currentDistance;

        }

    else if ( usersGuess < randomNumber )
    {
        message.setText( "Lower than correct guess." );

        lastDistance = currentDistance;

    }

        else
        {
            message.setText( "Congratulations, your guess is correct!" );

            guessInput.setEditable( false );
            countGuess = 0;

            findMiddleNumber();
        }
    }
}
public void findMiddleNumber()
{
    int num_of_guesses = 0; 

    Scanner inputs = new Scanner( System.in );

    int [] testArray = new int[ 20 ]; 

    do 
    { 
        if ( inputGuess != randomNumber ) 
        { 
            inputGuess  = inputs.nextInt();      

        } 
        else  
            testArray[ num_of_guesses ] = inputGuess; 
            num_of_guesses++; 

            if ( inputGuess >= randomNumber) 
            { 
                break;      
            }  

    }  
    while ( inputGuess != randomNumber); 

    middleNumber = testArray[( num_of_guesses)/ 2]; 

    System.out.printf( "\nMiddle is: " + middleNumber);

    finalOutput();
}


public void finalOutput()
{
    JOptionPane.showMessageDialog( null,"Congratulations, your guess "
        + "is correct." + "\n\n1. Middle number from all guessed "
        + "numbers by the user is: " + middleNumber + "\n\r2. Median "
        + " value of all guessed numbers by the user is: " 
        + medianValue + "\n\r3. A position (array index) of correctly "
        + "guessed number in sorted array is: " + positionIndex, 
        "Final Output", JOptionPane.PLAIN_MESSAGE );  

}

public static void main( String [] args )
{
    GuessGame application = new GuessGame();
    application.setDefaultCloseOperation( EXIT_ON_CLOSE );

}        

class GuessHandler implements ActionListener
{
    @Override
    public void actionPerformed ( ActionEvent event )
    {
        inputGuess = Integer.parseInt( guessInput.getText() );
        processGuessedNumber( inputGuess );

    }
}   
}

1 个答案:

答案 0 :(得分:2)

您需要在用户来时收集用户的输入并存储它们。在actionPerformed()JTextField的价值,将这些值存储在数组test[]中,然后调用ProcessGuessedNumber,如果匹配则为{{1}调用,我不知道为什么你曾经从findmidlenumber获取输入并在system.in匹配inputGuess时将它们存储在数组中,所以显而易见,您的randomNumber最新值将是最后一个,即inputGuess

当用户输入数组时输入数据,如果控件等于randomNumber,控件将自动移动到randomNumber。所以,在你的GuessHandler的middleNumer()

actionPerformed()

然后使用此数组计算您想要的任何内容,例如:

 public void actionPerformed ( ActionEvent event )
{
    inputGuess = Integer.parseInt( guessInput.getText() );
    test[i]= inputGuess;
    processGuessedNumber( inputGuess );
    i++;

}

<强> middleNumber = test[( i)/ 2]; System.out.printf( "\nMiddle is: " + middleNumber); finalOutput();

Complete Code