6 Replies - 254 Views - Last Post: 04 February 2018 - 02:05 PM Rate Topic: -----

#1 NotAJavaPro   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 03-February 18

Taking 3 Button inputs and adding it into a string

Posted 04 February 2018 - 12:38 PM

Hi,
I'm pretty new to Java and I've been stuck on a part of my program since last night. Basically what I'm trying to do is take in three JButton inputs and adding them to a string so I can compare it with the key value. But I'm having trouble figuring out how to do that. I've tried several loops and the current while loop in my code is wrong too. I figured out the reason why it's throwing an error is because I initialized b to be 0 in the beginning but I just can't figure out how else to take in input from an array of Buttons. I have an idea of how to compare the values afterwards with chatAt() but I can't get past this part. Any help on how to do what the title says will be appreciated.

I've tried using the " Object source to = event.getSource();" as well but I don't really understand how that works and I don't get any JButton values returned to my guess string when I used it. Here's what I have so far (the problem is around line 144):

 

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;



class Game extends JFrame{

    //there will be 10 number buttons
    public JButton[] button;
    //checks for win/lose
    //boolean checkWin;
    //will store guesses
    public String guess = "";
    //random number generator
    public int num1;
    public int num2;
    public int num3;
    public String key;
    public int b;
    //public int a = 0;
    public int ball;
    public int strike;
    public int number;
    
    Container contentPane = getContentPane();
    GamePanel panel = new GamePanel();
    JTextField display = new JTextField("Play Ball!!!");
    
    //non numeric buttons
    JButton button11 = new JButton("New Game");
    JButton button12 = new JButton("Clear");
                
      
    
    
    
    void initialize() {
        
        //setting metal look for Mac
        try {
            UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        //new instance for observer
        ButtonObserver observer = new ButtonObserver();
        
        //font of the textfield
        Font font1 = new Font("Courier New", Font.BOLD, 18);
        
        //display text on the North with font1 and editing disabled
       display.setFont(font1);
       display.setEditable(false);
       contentPane.add(display, BorderLayout.NORTH);
        
        //10 number buttons
        button = new JButton[10];
        
        //12 button grid on the south of content pane
        panel.setLayout(new java.awt.GridLayout(3, 4));
        contentPane.add(panel, BorderLayout.SOUTH);
        
        //adding all 12 buttons on the south of the content pane
        for (int i = 0; i < 10; i++) {
            button[i] = new JButton("" + i);
            button[i].addActionListener(observer);
            panel.add(button[i]);
            button[i].setEnabled(false);           
        }
        panel.add(button11);       
        panel.add(button12);
        button11.addActionListener(observer);
        button12.addActionListener(observer);
        button12.setEnabled(false);
        
   
        
    }
    
    
    public class ButtonObserver implements ActionListener{

        @Override
        
        public void actionPerformed(ActionEvent event){
            //Object source = event.getSource();
            //JButton button = (JButton) source; // type casting
            
            //new game button function
            if(event.getSource() == button11){
                
                    //generating random number
                    
                    int n = (int) (Math.random() * 1000);
                    num1 = n/100;
                    num2 = (n - (num1 * 100)) / 10;
                    num3 = n - ((num1 * 100) + (num2 * 10));
                    
                    //checking for duplicates and regenrating if not unique
                    while(num1 == num2 || num2 == num3 || num1 == num3){
                    n = (int) (Math.random() * 1000);
                    num1 = n/100;
                    num2 = (n - (num1 * 100)) / 10;
                    num3 = n - ((num1 * 100) + (num2 * 10));
                    }
                    
                    //showing the right key
                    if(n < 100){
                        key = "0" + String.valueOf(n);
                        //number = Integer.parseInt(key);
                        display.setText("Key = " + key);
                    }
                        else{
                           // number = n;
                            key = String.valueOf(n);
                           display.setText("Key = " + key);
                        }
                    
                    //enable buttons                   
                    for(int i = 0; i < 10; i++){
                        button[i].setEnabled(true);
                    } 
                }        
            
                    //clear button function
                    if(event.getSource() == button12){
                        display.setText("Key = " + key);
                        button12.setEnabled(false);
                        for(int i = 0; i < 10; i++){
                          button[i].setEnabled(true);
                        } 
                    }
                    
              //---------------------------------------      
 //--------get three Jbutton inputs inside a string to compare with the key value                   
                   if(event.getSource() != button11 && event.getSource() != button12){
                         int a = 0;
                        while(a<3){        
                                if((b >= 0 && b <= 9) && event.getSource() == button[b]){                                        
                                        
                                        //String label = button[b].getText(); 
                                       // System.out.println(label + " pressed");
                                        guess += "" + button[b].getText();
                                        //guess += "" + label;
                                        System.out.println(guess + " 2pressed");
                                        button[b].setEnabled(false);
                                    }                                                                       
                                    a++;
                                }    
                                                                                                                                                                                                                                            
                        // display message update
                        if(a == 2) {
                            for(int i = 0; i < 10; i++){
                                button[i].setEnabled(false);
                            }
                            display.setText("Key = " + key + "  |  Guess = " + guess + "  |  B = " + ball + "  S = " + strike);
                        }   else {
                                display.setText("Key = " + key + "  |  Guess = " + guess);
                            } 
                    }
                                                                                                      
        }
    }
    
}




PS. I know my indentations are messy, I had to delete and redo that part a lot trying out different loops, I cleaned it as much as I could.

PS. It's a bulls and cows game with three digits. So I have to stop taking inputs after the third button is clicked.

Is This A Good Question/Topic? 0
  • +

Replies To: Taking 3 Button inputs and adding it into a string

#2 NormR   User is offline

  • D.I.C Lover
  • member icon

Reputation: 691
  • View blog
  • Posts: 5,268
  • Joined: 25-December 13

Re: Taking 3 Button inputs and adding it into a string

Posted 04 February 2018 - 12:40 PM

Quote

throwing an error

Please copy the full text of the error message and paste it here. It has important info about the error.

How can the code be compiled and executed for testing?
I do not see a main() method.

This post has been edited by NormR: 04 February 2018 - 12:43 PM

Was This Post Helpful? 0
  • +
  • -

#3 NotAJavaPro   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 03-February 18

Re: Taking 3 Button inputs and adding it into a string

Posted 04 February 2018 - 12:53 PM

Here's the main method:

import javax.swing.JFrame;


public class MainBaseballGame {
    public static void main(String[] args) {
        Game frame = new Game();
        
        frame.setSize(500, 500);
        frame.setLocation(100, 100);
        frame.setTitle("New game");
        frame.initialize();
        
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
} 


It's not throwing an error that makes the code not run. I meant in the display tab it's supposed to display each of the buttons pressed when I press them but it's not showing that. it only shows null values or if I set b to 0 the it just shows 000. Sorry for the confusion. I can't edit my posts yet.

This post has been edited by ndc85430: 04 February 2018 - 01:03 PM
Reason for edit:: Removed quote of previous post. Please just press "Reply" in future.

Was This Post Helpful? 0
  • +
  • -

#4 NormR   User is offline

  • D.I.C Lover
  • member icon

Reputation: 691
  • View blog
  • Posts: 5,268
  • Joined: 25-December 13

Re: Taking 3 Button inputs and adding it into a string

Posted 04 February 2018 - 01:30 PM

Ok, that's a start. Now the code needs the GamePanel class to be able to compile.

What prints on the console when the program is executed?

Add some more print statements that print the values of the variables that are used so you can see what the computer sees when the program is executed.

Where are the null values coming from? Print the contents of the variables that show where the nulls come from.

This post has been edited by NormR: 04 February 2018 - 01:32 PM

Was This Post Helpful? 0
  • +
  • -

#5 NotAJavaPro   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 03-February 18

Re: Taking 3 Button inputs and adding it into a string

Posted 04 February 2018 - 01:44 PM

Right now the game class is empty. I'm going to add graphics in it but I'm trying to figure out the logic for the game first, that's where the ball and strike will come into play later in graphics. I get the null if I just declare String guess; without setting a value for it. I know why I'm getting all the errors, I just don't know how to go about fixing this problem at this point. Like, I'm not sure if I'm even supposed to use the loops I'm using and if not then which loops to nest which loop in. I tried playing around with the loops and trying out different combinations of for, if and while loops but none of them has worked so far. Are the loops I'm using the right ones in the right order?

 
import javax.swing.JPanel;


class GamePanel extends JPanel{
    
}



game class is empty right now.
Was This Post Helpful? 0
  • +
  • -

#6 NotAJavaPro   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 03-February 18

Re: Taking 3 Button inputs and adding it into a string

Posted 04 February 2018 - 01:50 PM

Edit: I know my logic for the loop of array buttons should be: if event.getSource is a button pressed and that button is any of button 0 through 9 then add the label of the button to the string. but this is my first time using array of JButton and I can't figure out how I can check for the 0 through 9 buttons with a loop and not have it initialize to 0. I think when I write event.getSource() == button[b], since b is initialized to 0 it's taking it as if I press button 0 then execute the loop instead of if button pressed is between 0 through 9. I can't figure out how to put this into code.
Was This Post Helpful? 0
  • +
  • -

#7 NormR   User is offline

  • D.I.C Lover
  • member icon

Reputation: 691
  • View blog
  • Posts: 5,268
  • Joined: 25-December 13

Re: Taking 3 Button inputs and adding it into a string

Posted 04 February 2018 - 02:05 PM

Quote

how I can check for the 0 through 9 buttons

The button has a text that the program can access with a method. Then use that value to make your decisions.


Why is there a while() loop using the variable a instead of a for loop? It looks like the loop should be a for loop.

This post has been edited by NormR: 04 February 2018 - 02:07 PM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1