Hi there,
I've searched through the forums but to no avail, many of the topics just seemed to make me more confused and it's starting to drive me up insane! I think I could be here a fair bit in the next few weeks too having to redo assignments; Java, specifically Swing is not my friend and I feel much more like giving up. Hopefully I'm not as far as I think (though I find that hard to believe)
Anyway, this current app I'm working on is the
Guessing Game
Basically, you choose a number between 1-1,000, which the computer has to guess and you eliminate responses by clicking High / Low or Correct (to end the loop)
So effectively
int min=0,max=1000;
And you effectively have to half the number of possible numbers by each click
int guess=(max+min)/2;
The error Java keeps throwing up now (when I thought I'd finally got it working, though when I removed some parts I saw I'd looped all the buttons so the app just goes mad really printing button after button.. I'm sure you know how I mean)
Cannot refer to a non-final variable guess inside an inner class defined in a different method
Anyway, here's my code so far
import javax.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class guessingGame {
public static void main(String args[])
{
// Create the window
JFrame frame = new JFrame("Guessing Game");
frame.setVisible(true);
frame.setSize(400,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
// Begin loop, generate number between 0-1000
final boolean finished=false;
int min=0,max=1000;
// Create the buttons
while (!finished)
{
if (max<min)
{
JLabel cheat = new JLabel("You cheated");
panel.add(cheat);
}
else
{
JButton endButton = new JButton("Correct");
panel.add(endButton);
endButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
{
finished=true;
}
}
});
int guess=(max+min)/2;
JLabel guessLabel = new JLabel("My guess is:" + guess);
panel.add(guessLabel);
JButton highButton = new JButton("High");
panel.add(highButton);
highButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int max=guess-1;
JLabel answer = new JLabel ("My new guess:" + max);
}
});
JButton lowButton = new JButton("Low");
panel.add(lowButton);
lowButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int min=guess+1;
JLabel answer = new JLabel ("My new guess:" + min);
}
});
}
}
}}
Thanks so much, please don't hesistate to ask any questions - I need to learn otherwise I'll be hopeless at Swing