Results 1 to 11 of 11
  1. #1
    byron is offline Member
    Join Date
    Feb 2008
    Posts
    5
    Rep Power
    0

    Unhappy Defective code for dice, help please?

    I'm using NetBeans to create a dice program. As such, the entire code is automatically created, except for the following:
    private void rollActionPerformed(java.awt.event.ActionEvent evt) {
    Random dice = new Random();
    int throw = dice.nextInt(6) + 1;
    number.setText(throw);
    }
    (I also put "import java.util.Random;" at the top of the program, just below package declaration)

    My program (which has a GUI, which is why I used NetBeans) consists of a JFrame, 2 JLabels (one is called "title" and is the title of the program ["Virtual Dice"], and the other is called "number", and is where I try to set the random number the program generated.) and a JButton (titled "roll") which makes the program

    Anyways, NetBeans tells me the last two lines are bad. The second to last one says " ';' expected/not a statement/illegal start of expression" (I have replaced line breaks with a slash in the above.) The last line is bad because "illegal start of expression/illegal start of expression".

    So what do I need to do it to fix this program?

    Peace,
    Byron

    P.S., here is the entire source code:

    /*
    * virtualDice.java
    *
    * Created on February 16, 2008, 8:32 AM
    */

    package virtualDice;

    import java.util.Random;
    /**
    *
    * @author Byron&Cheryl
    */
    public class virtualDice extends javax.swing.JFrame {

    /** Creates new form virtualDice */
    public virtualDice() {
    initComponents();
    }

    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

    title = new javax.swing.JLabel();
    number = new javax.swing.JLabel();
    roll = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstan ts.EXIT_ON_CLOSE);

    title.setFont(new java.awt.Font("Tahoma", 0, 24));
    title.setText("Virtual Dice");
    title.setHorizontalTextPosition(javax.swing.SwingC onstants.CENTER);

    number.setFont(new java.awt.Font("Tahoma", 0, 36));
    number.setText("0");

    roll.setText("Roll!");
    roll.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    rollActionPerformed(evt);
    }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(160, 160, 160)
    .addComponent(number, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(layout.createSequentialGroup()
    .addGap(145, 145, 145)
    .addComponent(roll))
    .addGroup(layout.createSequentialGroup()
    .addGap(108, 108, 108)
    .addComponent(title)))
    .addContainerGap(116, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(6, 6, 6)
    .addComponent(title)
    .addPreferredGap(javax.swing.LayoutStyle.Component Placement.UNRELATED)
    .addComponent(number, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.Component Placement.RELATED)
    .addComponent(roll)
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_S IZE, Short.MAX_VALUE))
    );

    pack();
    }// </editor-fold>

    private void rollActionPerformed(java.awt.event.ActionEvent evt) {
    Random dice = new Random();
    int throw = dice.nextInt(6) + 1;
    number.setText(throw);
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new virtualDice().setVisible(true);
    }
    });
    }

    // Variables declaration - do not modify
    private javax.swing.JLabel number;
    private javax.swing.JButton roll;
    private javax.swing.JLabel title;
    // End of variables declaration

    }
    Last edited by byron; 02-16-2008 at 04:16 PM.

  2. #2
    kurtulas is offline Member
    Join Date
    Feb 2008
    Posts
    2
    Rep Power
    0

    Default

    Hi Byron,

    Im not 100% with this but im pretty sure you cannot use 'throw' as a declared variable as it is a key word in java.

    Hope this helps.

    Kurt

  3. #3
    byron is offline Member
    Join Date
    Feb 2008
    Posts
    5
    Rep Power
    0

    Default

    Quote Originally Posted by kurtulas View Post
    Hi Byron,

    Im not 100% with this but im pretty sure you cannot use 'throw' as a declared variable as it is a key word in java.

    Hope this helps.

    Kurt
    Okay, I changed "throw" to "numb" (short for number), and then tried to compile it. NetBeans now says:
    C:\Users\Byron&Cheryl\Documents\NetBeansProjects\V irtual Dice\src\virtualDice\virtualDice.java:84: setText(java.lang.String) in javax.swing.JLabel cannot be applied to (int)
    Java is starting to give me a headache... :)

  4. #4
    Bluefox815 is offline Member
    Join Date
    Feb 2008
    Location
    Oregon, USA
    Posts
    49
    Rep Power
    0

    Default

    setText(java.lang.String) tells you what the method needs to be given (a String object)
    but you gave it an int.
    Java Code:
    private void rollActionPerformed(java.awt.event.ActionEvent evt) {
    Random dice = new Random();
    int throw = dice.nextInt(6) + 1;
    number.setText(throw);
    }
    throw is an int and you tried to give throw (or numb) to setText()

    Try this instead
    Java Code:
    private void rollActionPerformed(java.awt.event.ActionEvent evt) {
    Random dice = new Random();
    Integer numb = dice.nextInt(6) + 1;
    number.setText(numb.toString());
    }
    numb is now an Integer and an Integer can be changed to a String with .toString()

    Also, you should put
    Java Code:
    import java.awt.event.ActionEvent;
    So you only have to write
    Java Code:
    private void rollActionPerformed(ActionEvent evt) {
    }
    And lastly, it probably wont know what number is because your variable declarations (fields) are at the bottom of the file, you should put them directly under your class declaration
    Java Code:
    // package and import statements
    
    public class virtualDice extends javax.swing.JFrame {
    
    // variable declarations
    
    // all your other code
    
    }
    Last edited by Bluefox815; 02-16-2008 at 08:06 PM.

  5. #5
    byron is offline Member
    Join Date
    Feb 2008
    Posts
    5
    Rep Power
    0

    Default

    Okay here is my new code:

    /*
    * virtualDice.java
    *
    * Created on February 16, 2008, 8:32 AM
    */

    package virtualDice;

    import java.util.Random;
    /**
    *
    * @author Byron&Cheryl
    */
    public class virtualDice extends javax.swing.JFrame {

    // Variables declaration - do not modify
    private javax.swing.JLabel number;
    private javax.swing.JButton roll;
    private javax.swing.JLabel title;
    // End of variables declaration
    /** Creates new form virtualDice */

    public virtualDice() {
    initComponents();
    }

    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

    title = new javax.swing.JLabel();
    number = new javax.swing.JLabel();
    roll = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstan ts.EXIT_ON_CLOSE);

    title.setFont(new java.awt.Font("Tahoma", 0, 24));
    title.setText("Virtual Dice");
    title.setHorizontalTextPosition(javax.swing.SwingC onstants.CENTER);

    number.setFont(new java.awt.Font("Tahoma", 0, 36));
    number.setText("0");

    roll.setText("Roll!");
    roll.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    rollActionPerformed(evt);
    }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(160, 160, 160)
    .addComponent(number, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(layout.createSequentialGroup()
    .addGap(145, 145, 145)
    .addComponent(roll))
    .addGroup(layout.createSequentialGroup()
    .addGap(108, 108, 108)
    .addComponent(title)))
    .addContainerGap(116, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(6, 6, 6)
    .addComponent(title)
    .addPreferredGap(javax.swing.LayoutStyle.Component Placement.UNRELATED)
    .addComponent(number, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.Component Placement.RELATED)
    .addComponent(roll)
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_S IZE, Short.MAX_VALUE))
    );

    pack();
    }// </editor-fold>

    private void rollActionPerformed(java.awt.event.ActionEvent evt) {
    Random dice = new Random();
    int numb = dice.nextInt(6) + 1;
    number.setText(numb.toString());
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new virtualDice().setVisible(true);
    }
    });
    }


    }
    Now NetBeans says:

    C:\Users\Byron&Cheryl\Documents\NetBeansProjects\V irtual Dice\src\virtualDice\virtualDice.java:90: int cannot be dereferenced
    to the line that says

    number.setText(numb.toString());
    What does dereferencing mean? I'm so confused!

  6. #6
    Bluefox815 is offline Member
    Join Date
    Feb 2008
    Location
    Oregon, USA
    Posts
    49
    Rep Power
    0

    Default

    Java Code:
    private void initComponents() {
    
    title = new javax.swing.JLabel();
    number = new javax.swing.JLabel();
    roll = new javax.swing.JButton();
    
    setDefaultCloseOperation(javax.swing.WindowConstan ts.EXIT_ON_CLOSE);
    
    title.setFont(new java.awt.Font("Tahoma", 0, 24));
    title.setText("Virtual Dice");
    title.setHorizontalTextPosition(javax.swing.SwingC onstants.CENTER);
    
    number.setFont(new java.awt.Font("Tahoma", 0, 36));
    number.setText("0");
    
    roll.setText("Roll!");
    roll.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    rollActionPerformed(evt);
    }
    });
    First of all, what is that parenthesis at the end? It shouldn't be there, neither should the semicolon, they will probably give you problems later. ALSO make sure you replace it with a bracket ( } ), you are one short.

    EDIT: I'm sorry, that parenthesis and semi-colon are required, my apologies.

    And for the dereferencing, you tried to use toString() on an int, and not on an Integer object. You see, int is a primitive data type, like boolean, or double, or byte.
    Integer is a class file, like String, or JFrame, or virtualDice (btw, you should rename it to VirtualDice, class names are just supposed to start with a capital, you named everything else right).
    Integer actually has a method called toString() for you to use, not the int data type. So you need to do this
    Java Code:
    private void rollActionPerformed(java.awt.event.ActionEvent evt) { 
    Random dice = new Random();
    Integer numb = new Integer(dice.nextInt(6) + 1);
    number.setText(numb.toString());
    }
    That part should work perfectly :)
    Last edited by Bluefox815; 03-12-2008 at 12:13 AM.

  7. #7
    byron is offline Member
    Join Date
    Feb 2008
    Posts
    5
    Rep Power
    0

    Unhappy

    Okay, I decided to give up on the above pregenerated code. I learned a little swing, and made a new code.

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    
      public class diceGUI {
        public static void main(String[] args) {
    	JFrame frame = new JFrame("Virtual Dice");
    	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	Box f = Box.createVerticalBox();
    
    	
    	Random generator = new Random(); //initiates the random generator
    	
      	//titleLabel
    	JLabel titleLabel = new JLabel("<html><big>Virtual Dice</big></html>");
    	f.add(titleLabel);
    	f.add(Box.createVerticalStrut(25));
    
      	//resultLabel
    	JLabel resultLabel = new JLabel("Roll: --");
    	f.add(resultLabel);
    	f.add(Box.createVerticalStrut(25));
      	
    	// rollButton
    	JButton rollButton = new JButton("Roll!");
    	rollButton.addActionListener(new ActionListener() {
    		public void actionPerformed (ActionEvent event) {
    			int diceThrow = generator.nextInt(6) + 1;  \\[b]javac says:  "local variable generator is accessed from within inner class.  Needs to be declared final."[/b]
    			resultLabel.setText("Roll: " +diceThrow);  \\[b]javac says:  ""local variable resultLabel is accessed from within inner class.  Needs to be declared final."[/b]
    
    		}
    	});
    	f.add(rollButton);
    
    	frame.add(f, BorderLayout.CENTER);
    	frame.setSize(150,200);
    	frame.setVisible(true);
        }
      }
    My problem,as I noted in the code as comments, is that I need to declare local variables as final. So a few questions arise:

    What is a local variable?
    what does it mean to declare a variable as final.
    Why is it necessary to declare it as final?

    Thanks, and peace to all!
    Byron

  8. #8
    Bluefox815 is offline Member
    Join Date
    Feb 2008
    Location
    Oregon, USA
    Posts
    49
    Rep Power
    0

    Default

    javac is saying that because your local variables resultLabel and generator, are trying to be used inside of your actionListener, this compiles and runs perfectly:

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    
      public class DiceGUI {
    
        private static JLabel resultLabel;
        private static Random generator;
    
        public static void main(String[] args) {
    
    	JFrame frame = new JFrame("Virtual Dice");
    	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	Box f = Box.createVerticalBox();
    
    	
    	generator = new Random(); //initiates the random generator
    	
      	//titleLabel
    	JLabel titleLabel = new JLabel("<html><big>Virtual Dice</big></html>");
    	f.add(titleLabel);
    	f.add(Box.createVerticalStrut(25));
    
      	//resultLabel
    	resultLabel = new JLabel("Roll: --");
    	f.add(resultLabel);
    	f.add(Box.createVerticalStrut(25));
      	
    	// rollButton
    	JButton rollButton = new JButton("Roll!");
    	rollButton.addActionListener(new ActionListener() {
    		public void actionPerformed (ActionEvent event) {
    			int diceThrow = generator.nextInt(6) + 1;
    			resultLabel.setText("Roll: " +diceThrow);
    
    		}
    	});
    	f.add(rollButton);
    
    	frame.add(f, BorderLayout.CENTER);
    	frame.setSize(150,200);
    	frame.setVisible(true);
        }
      }
    By the way, nice work on doing your own hardcode :) you only had one problem.

  9. #9
    byron is offline Member
    Join Date
    Feb 2008
    Posts
    5
    Rep Power
    0

    Default

    Quote Originally Posted by Bluefox815 View Post
    javac is saying that because your local variables resultLabel and generator, are trying to be used inside of your actionListener, this compiles and runs perfectly:
    Thanks, it does work. I'll go through the code a little later, and disect the differences and try to understand why.

    Quote Originally Posted by Bluefox815 View Post
    By the way, nice work on doing your own hardcode :) you only had one problem.
    Thanks. At least i know my studying paid off! One question, how can I center the button and JLabels? I can't figure out how to do that.

    Well, anyways, thanks!!! I really appreciate it!!!

  10. #10
    King8654's Avatar
    King8654 is offline Member
    Join Date
    Apr 2008
    Posts
    9
    Rep Power
    0

    Default

    To center the JLabel, just need:

    Example from code actually working on:

    this.add(_aLabel, java.awt.BorderLayout.NORTH);
    _aLabel.setHorizontalAlignment(JLabel.CENTER);

  11. #11
    Bluefox815 is offline Member
    Join Date
    Feb 2008
    Location
    Oregon, USA
    Posts
    49
    Rep Power
    0

    Default

    if you invoke setAlignmentX(0.5f) for ALL components AND you use a JPanel with a BoxLayout, they will all be centered. I decided to rewrite the DiceGUI class so it uses this. Also, I rewrote the code to help you understand why the label had to be global (added comments explaining this)
    NOTE: This WILL NOT compile! You cannot use the keyword "this" inside of a static method.
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    
      public class DiceGUI implements ActionListener { // make DiceGUI an ActionListener object (DiceGUI now needs to have the method actionPerformed(ActionEvent)
    
        private static JLabel resultLabel;
        private static Random generator;
    
        // You see, actionPerformed is a separate method, and initializing resultLabel in main means this
        // method cannot see the variable because it is destroyed as soon as main ends
    
        public void actionPerformed (ActionEvent event) {
    	int diceThrow = generator.nextInt(6) + 1;
    	resultLabel.setText("Roll: " +diceThrow);
        }
    
        public static void main(String[] args) {
    
    	JFrame frame = new JFrame("Virtual Dice");
    	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	JPanel f = new JPanel();
    	f.setLayout(new BoxLayout(f, BoxLayout.Y_AXIS)); // BoxLayout.Y_AXIS makes the components go top to bottom
    
    	
    	generator = new Random(); //initiates the random generator
    	
      	//titleLabel
    	JLabel titleLabel = new JLabel("<html><big>Virtual Dice</big></html>");
    	titleLabel.setAlignmentX(0.5f);
    	f.add(titleLabel);
    	f.add(Box.createVerticalStrut(25));
    
      	//resultLabel
    	resultLabel = new JLabel("Roll: --");
    	resultLabel.setAlignmentX(0.5f);
    	f.add(resultLabel);
    	f.add(Box.createVerticalStrut(25));
      	
    	// rollButton
    	JButton rollButton = new JButton("Roll!");
    	rollButton.setAlignmentX(0.5f);
    	rollButton.addActionListener(this); // this (DiceGUI) implements ActionListener and is now an ActionListener object (this is were the keyword 'this' is used inside static method main(String[]))
    	f.add(rollButton);
    
    	frame.add(f, BorderLayout.CENTER);
    	frame.setSize(150,200);
    	frame.setVisible(true);
        }
      }
    However, this WILL compile (I gave you the code with errors to make it easier to understand the important concepts).

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    
      public class DiceGUI implements ActionListener {
    
        private static JLabel resultLabel;
        private static Random generator;
    
        public void actionPerformed (ActionEvent event) {
    	int diceThrow = generator.nextInt(6) + 1;
    	resultLabel.setText("Roll: " +diceThrow);
        }
    
        public void createGUI() {
    
    	JFrame frame = new JFrame("Virtual Dice");
    	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	JPanel f = new JPanel();
    	f.setLayout(new BoxLayout(f, BoxLayout.Y_AXIS));
    	
    	generator = new Random(); //initiates the random generator
    	
      	//titleLabel
    	JLabel titleLabel = new JLabel("<html><big>Virtual Dice</big></html>");
    	titleLabel.setAlignmentX(0.5f);
    	f.add(titleLabel);
    	f.add(Box.createVerticalStrut(25));
    
      	//resultLabel
    	resultLabel = new JLabel("Roll: --");
    	resultLabel.setAlignmentX(0.5f);
    	f.add(resultLabel);
    	f.add(Box.createVerticalStrut(25));
      	
    	// rollButton
    	JButton rollButton = new JButton("Roll!");
    	rollButton.setAlignmentX(0.5f);
    	rollButton.addActionListener(this);
    	f.add(rollButton);
    
    	frame.add(f, BorderLayout.CENTER);
    	frame.setSize(150,200);
    	frame.setVisible(true);
        }
    
        public static void main(String[] args) {
    	SwingUtilities.invokeLater(new Runnable() {
    		public void run() {
    			new DiceGUI().createGUI();
    		}
    	});
        }
    
      }
    Last edited by Bluefox815; 04-01-2008 at 06:53 AM.

Similar Threads

  1. Roll 2-Dice "Pig" Game Help
    By King8654 in forum AWT / Swing
    Replies: 7
    Last Post: 04-07-2008, 06:58 PM
  2. I need help fixing my code.. or non code?
    By MrHuggykins in forum New To Java
    Replies: 1
    Last Post: 03-19-2008, 10:12 PM
  3. Help debugging a dice game
    By Windoze in forum New To Java
    Replies: 7
    Last Post: 11-22-2007, 01:01 AM
  4. help debugging a dice game
    By Windoze in forum Advanced Java
    Replies: 0
    Last Post: 11-16-2007, 10:28 PM
  5. Replies: 1
    Last Post: 04-26-2007, 03:52 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •