Results 1 to 14 of 14
Like Tree3Likes
  • 3 Post By Fubarable

Thread: Not working!

  1. #1
    verde is offline Member
    Join Date
    Apr 2012
    Posts
    5
    Rep Power
    0

    Default Not working!

    Hello. I've got a problem. I'm new to Java and I can't find the problem in my program. My program is supposed to take rows from a csv file into a 2d array and then do a little game of question-answer. In the first column of the array are the answers and in the last column are the correct answers. In the GUI if you press the right answer you'll get to the next question but if you press the wrong one you'll get prompted with "Wrong Answer". BUT this is not what my code will do: If you press the right button you'll advance to next question but you'll also get prompted with "Wrong Answer" or other times you'll get prompted 3-4 times with the same message or a question will be skipped (but you can see questioncounter is incremented). Please run it and see. I don't know what to do.

    JAVA CODE: JAVA CODE HERE
    File intrebari.csv: intrebari.csv

    The file intrebari.csv is a csv with this format Quetion|Answer1|Answer2|Answer3|Answer4

    Java Code:
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Random;
    import java.util.StringTokenizer;
    
    import javax.swing.ButtonGroup;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    
    public class plma implements ActionListener {
    	// String for Correct Answer
    	String correctanswer;
    	// Pannels for points&questions counters, questions and answers
    	JPanel panel1 = new JPanel();
    	JPanel panel2 = new JPanel();
    	JPanel panel3 = new JPanel();
    	// Buttons for answers
    	JButton b1 = new JButton("null");
    	JButton b2 = new JButton("null");
    	JButton b3 = new JButton("null");
    	JButton b4 = new JButton("null");
    	// Label for question
    	JLabel text = new JLabel();
    	// Label for questions /points counters
    	JLabel questioncounterlabel = new JLabel();
    	JLabel pointscounterlabel = new JLabel();
    	// Group Buttons
    	ButtonGroup buttons = new ButtonGroup();
    
    	Random ir = new Random();
    	String[][] sir2;
    	// Initialize points and questions counters variables
    	int questionscounter = 0;
    	int pointscounter = 0;
    
    	// Get the questiontextfrom the csv file and store it in a 2d array with the
    	// first
    	// coloumn storing the questions and the last coloum storing the correct
    	// answers
    	public void getQuestionsFromFile(String[][] sir) throws IOException {
    		File file = new File("intrebari.csv");
    		int row = 0;
    		int col = 0;
    		BufferedReader reader = new BufferedReader(new FileReader(file));
    		String line = null;
    
    		while ((line = reader.readLine()) != null && row < sir.length) {
    			StringTokenizer st = new StringTokenizer(line, "|");
    			while (st.hasMoreTokens()) {
    				sir[row][col] = st.nextToken();
    				col++;
    			}
    			col = 0;
    			row++;
    		}
    	}
    
    	// Fetch the 2d array from the main function and store it
    	public void keepQuestionsArraySafe(String sir[][]) {
    		sir2 = sir;
    	}
    
    	// Generate Frame with its properties; add panels, buttons to it
    	public void frameGenerator(JFrame fereastra) {
    		GridLayout layout = new GridLayout(3, 1);
    		fereastra.setLayout(layout);
    		fereastra.setTitle("Intrebari si raspunsuri");
    		fereastra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		fereastra.setSize(800, 600);
    		fereastra.setVisible(true);
    		fereastra.setLocationRelativeTo(null);
    		fereastra.getContentPane().add(panel3);
    		fereastra.getContentPane().add(panel2);
    		fereastra.getContentPane().add(panel1);
    		buttons.add(b1);
    		buttons.add(b2);
    		buttons.add(b3);
    		buttons.add(b4);
    		panel1.add(b1);
    		panel1.add(b2);
    		panel1.add(b3);
    		panel1.add(b4);
    		panel2.add(text);
    		panel3.add(questioncounterlabel);
    		panel3.add(pointscounterlabel);
    
    	}
    
    	public void questionGenerator() {
    		// Increment questions counter
    		questionscounter++;
    		String[][] sir3 = new String[7][5];
    		// Add 1 point if questions number is bellow 5 and 5 points if it's
    		// over or equally to 5
    		if (questionscounter < 5) {
    			++pointscounter;
    		} else if (questionscounter >= 5) {
    			pointscounter = pointscounter + 5;
    		}
    		// Print questions number and points in panel3
    		questioncounterlabel
    				.setText("Number of questions: " + questionscounter);
    		pointscounterlabel.setText("Number of points: " + pointscounter);
    		// Get random number which will be used to access a random row
    		int x = ir.nextInt(7);
    		// Make a new array based on the initial array (because the initial
    		// array needs to stay the same)
    		for (int i = 0; i < 5; i++) {
    			sir3[x][i] = sir2[x][i];
    		}
    		// Store the last column string (which is the correct answer)
    		correctanswer = sir2[x][4];
    		// Delete white spaces from the string
    		correctanswer = correctanswer.replaceAll(" ", "");
    		// Print in the console the correct answer
    		System.out.println(correctanswer);
    		// Shuffle the answers
    		Random shuffle = new Random();
    		for (int i = 1; i <= 4; i++) {
    			int RandomPosition = 1 + shuffle.nextInt(4);
    			String temp = sir3[x][i];
    			sir3[x][i] = sir3[x][RandomPosition];
    			sir3[x][RandomPosition] = temp;
    		}
    		// Add answers to buttons and question to label to panel2
    		text.setText(sir3[x][0]);
    		b1.setText(sir3[x][1]);
    		b2.setText(sir3[x][2]);
    		b3.setText(sir3[x][3]);
    		b4.setText(sir3[x][4]);
    		b1.addActionListener(this);
    		b2.addActionListener(this);
    		b3.addActionListener(this);
    		b4.addActionListener(this);
    
    	}
    
    	// Check if answer is correct: if the string from the button pressed is
    	// equal to the value stored in correctanswer variable
    	public void actionPerformed(ActionEvent e) {
    
    		String btntext = ((JButton) e.getSource()).getText();
    		btntext = btntext.replaceAll(" ", "");
    		if (correctanswer.equals(btntext)) {
    			questionGenerator();
    		}
    
    		else {
    			JOptionPane.showMessageDialog(null, "Wrong answer");
    		}
    	}
    
    	public static void main(String[] args) throws IOException {
    		String[][] intrebari = new String[7][5];
    		JFrame fereastra = new JFrame();
    
    		plma gf = new plma();
    		gf.getQuestionsFromFile(intrebari);
    		gf.keepQuestionsArraySafe(intrebari);
    		gf.frameGenerator(fereastra);
    		gf.questionGenerator();
    
    	}
    }
    Last edited by verde; 04-15-2012 at 10:39 AM.

  2. #2
    shall is offline Senior Member
    Join Date
    Apr 2012
    Posts
    199
    Rep Power
    0

    Default Re: Not working!

    Just taking a quick look. What if random position comes up with the same number twice?

    Java Code:
            for (int i = 1; i <= 4; i++)
            {
                int RandomPosition = 1 + shuffle.nextInt(4);
                String temp = sir3[x][i];
                sir3[x][i] = sir3[x][RandomPosition];
                sir3[x][RandomPosition] = temp;
            }

  3. #3
    shall is offline Senior Member
    Join Date
    Apr 2012
    Posts
    199
    Rep Power
    0

    Default Re: Not working!

    I think the problem is that the buttons' addActionListener is being called more than once. See the questionGenerator function.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Not working!

    Just FYI: Many of us will wait for you to post your code here to the forum before reading it.

  5. #5
    shall is offline Senior Member
    Join Date
    Apr 2012
    Posts
    199
    Rep Power
    0

    Default Re: Not working!

    He's already posted his code - right below his first post. Is that what you are talking about?

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Not working!

    Quote Originally Posted by shall View Post
    He's already posted his code - right below his first post. Is that what you are talking about?
    All I see is a link. Again, many are wary about clicking on links and would like to see the code posted in the forum. Also my feeling is, if he wants us to put in the effort to offer free help, he should put in the effort to post relevant well formatted and commented code.
    DarrylBurke, JosAH and noobplus like this.

  7. #7
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,189
    Rep Power
    19

    Default Re: Not working!

    Added to which, for many members, file sharing sites are blocked by a corporate firewall.

    I'm not blocked, but I don't click links. My choice. You want help, post the code here. If it's too long to be posted here, then it's too long for me to go through.

    I also don't read code that is badly formatted, contains gross violations of the coding conventions or after several requests to the poster, is still without the code formatting tags. Again, that's my choice.

    Those who feel an obligation to put in extra effort to assist the lazy and inconsiderate are free to do otherwise. That's their choice.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  8. #8
    verde is offline Member
    Join Date
    Apr 2012
    Posts
    5
    Rep Power
    0

    Default Re: Not working!

    Hey. No problem posting the code to the forum. Now it's in the first post.

  9. #9
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,189
    Rep Power
    19

    Default Re: Not working!

    In future, please don't edit your posts after there are responses (except maybe to correct a typo). this causes the responses to appear irrelevant and makes the thread difficult to follow.

    Just post a response with anything you wish to add.

    Anyhow, you already have the answer at #3.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  10. #10
    verde is offline Member
    Join Date
    Apr 2012
    Posts
    5
    Rep Power
    0

    Default Re: Not working!

    Quote Originally Posted by shall View Post
    I think the problem is that the buttons' addActionListener is being called more than once. See the questionGenerator function.
    What is wrong there? Why it''s called more than once and how can I fix it? Thanks

  11. #11
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,189
    Rep Power
    19

    Default Re: Not working!

    Each time that method executes you have one more ActionListener added. Doesn't look like that's what you wanted, so add the action listener in code that runs only once. Like in the constructor.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  12. #12
    verde is offline Member
    Join Date
    Apr 2012
    Posts
    5
    Rep Power
    0

    Default Re: Not working!

    Thanks for the reply. Can you please describe a little ? I don't quite understand what I have to do to get it working.

  13. #13
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Not working!

    Quote Originally Posted by verde View Post
    Thanks for the reply. Can you please describe a little ? I don't quite understand what I have to do to get it working.
    It's pretty straightforward what he's recommending. You're adding your ActionListeners to the JButtons in the questionGenerator method where they will be re-added every time that method is called. Simply add the listeners in the constructor. If you don't understand this advice, please let us know *specifically* what confuses you.

  14. #14
    verde is offline Member
    Join Date
    Apr 2012
    Posts
    5
    Rep Power
    0

    Default Re: Not working!

    That fixed it! Many thanks to both of you!

Similar Threads

  1. Collisions are working & not working
    By Jayayoh in forum Java 2D
    Replies: 1
    Last Post: 06-24-2011, 05:21 PM
  2. Replies: 2
    Last Post: 01-04-2011, 04:30 AM
  3. Why is my Do/While Not working?
    By Meta in forum New To Java
    Replies: 1
    Last Post: 05-11-2010, 06:05 PM
  4. working with JC
    By yuhobebbho in forum New To Java
    Replies: 0
    Last Post: 02-10-2010, 11:22 PM
  5. Replies: 8
    Last Post: 05-28-2008, 07:00 AM

Posting Permissions

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