Welcome to Dream.In.Code
Become a Java Expert!

Join 150,033 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,591 people online right now. Registration is fast and FREE... Join Now!




Vector search

2 Pages V  1 2 >  
Reply to this topicStart new topic

Vector search

hezfast2
14 Jun, 2008 - 08:10 AM
Post #1

New D.I.C Head
*

Joined: 19 May, 2008
Posts: 16

Hello, I've written a multiple choice question version of a Hangman game. Everything works 'except' I don't want questions asked more than once. I've come up with a search algorithm, but I obviously don't have it correct, or I'm going wrong somewhere, It compiles but the questions still repeat. here's what I have so far: Any help or advice would be greatly appreciated.
CODE

        questionNum = (int)(Math.random() * 10);  
        while (isUsed)
        {
        searchResult = seqSearch(usedList, questionNum);
        if (searchResult == -1)
        {
            isUsed = false;
      }//end if
        else
            questionNum = (int)(Math.random() * 10);
        usedList.addElement(questionNum);
        }//end while
        QuestionInfo curQues = new QuestionInfo(questionObj[questionNum]);
        
        displayQuestion(questionObj, curQues, questionNum);

CODE

    public int seqSearch(Vector<Integer> usedList, int questionNum)
    {
         boolean found = false;
        
         for (Integer num : usedList)
             if (num == questionNum)
              {
                  found = true;
                    break;
              }
         if (found)
             return 1;
              else
                 return -1;
    }

User is offlineProfile CardPM
+Quote Post

gl3thr0
RE: Vector Search
14 Jun, 2008 - 08:57 AM
Post #2

D.I.C Head
**

Joined: 27 Oct, 2007
Posts: 209



Thanked: 3 times
My Contributions
do u have the rest of your code?
User is offlineProfile CardPM
+Quote Post

hezfast2
RE: Vector Search
14 Jun, 2008 - 09:18 AM
Post #3

New D.I.C Head
*

Joined: 19 May, 2008
Posts: 16

Here's my entire code:

CODE

//Import packages
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class AdvancedJavaHangman extends JFrame
{
    private static final int WIDTH = 600;
    private static final int HEIGHT = 1000;
    private static int numOfWrongAns = 0;
    private static int score = 0;
    private static int quizQuesNum = 0;
    private static boolean isUsed;
    private static int searchResult;
    
    ImageIcon icon = new ImageIcon("Hangman.jpg", "Hangman");

    
        //Instance variables
    private JLabel questionLabel, hangLabel;
    
    private JButton ansButtonA, ansButtonB, ansButtonC, ansButtonD, exitButton;
    private ButtonHandler ansButtonHandler;

    public AdvancedJavaHangman()
    {    
        
        String[] question = new String[10];                    //array to hold all questions
        String[] ansA = new String[10];                        //array to hold all answer A's
        String[] ansB = new String[10];                        //array to hold all answer B's
        String[] ansC = new String[10];                        //array to hold all answer C's
        String[] ansD = new String[10];                        //array to hold all answer D's
        String[] correctAns = new String[10];                //array to hold all correct answer letters

      Vector<Integer> usedList = new Vector<Integer>();//vector to hold used question numbers

        int questionNum;
        
        try
        {
            BufferedReader in = new BufferedReader(new FileReader("JavaQuestions.txt"));

                //read questions and answers into arrays
            for(int num = 0; num < 10; num++)
            {
                question[num] = in.readLine();
                ansA[num] = in.readLine();
                ansB[num] = in.readLine();
                ansC[num] = in.readLine();
                ansD[num] = in.readLine();
                correctAns[num] = in.readLine();
            }//end for
            in.close();
            
        }//end try
            
        catch(IOException ioe)
        {
            System.out.println(ioe.toString());
        }//end catch
        
        QuestionInfo[] questionObj = new QuestionInfo[10];
        
        for(int x = 0; x < 10; x++)
        {
            questionObj[x] = new QuestionInfo(question[x], ansA[x], ansB[x], ansC[x], ansD[x], correctAns[x]);
        }
        questionNum = (int)(Math.random() * 10);
        isUsed = true;
        while (isUsed)
        {
            searchResult = seqSearch(usedList, questionNum);
            if (searchResult == -1)
            {
                isUsed = false;
          }//end if
            else
                questionNum = (int)(Math.random() * 10);
        }//end while
        usedList.addElement(questionNum);
        QuestionInfo curQues = new QuestionInfo(questionObj[questionNum]);
        displayQuestion(questionObj, curQues, questionNum);
    }//end method AdvancedJavaHangman    
    
    private class ButtonHandler implements ActionListener
    {    
    
        private QuestionInfo currentQues = new QuestionInfo();

        public ButtonHandler()
        {
            currentQues = new QuestionInfo();
            
        }
    
        public ButtonHandler(QuestionInfo currentQuestion)
        {
            currentQues = new QuestionInfo(currentQuestion);
        }
        
        public void actionPerformed(ActionEvent e)
        {
            if (e.getActionCommand().equals("Exit"))
                System.exit(0);
            else if (e.getActionCommand().equals(currentQues.getAnsA()))
            {    
                String userAns = "A";
                checkAnswer(currentQues, userAns);
            }//end if
            else if (e.getActionCommand().equals(currentQues.getAnsB()))
            {
                String userAns = "B";
                checkAnswer(currentQues, userAns);
            }//end if
            else if (e.getActionCommand().equals(currentQues.getAnsC()))
            {
                String userAns = "C";
                checkAnswer(currentQues, userAns);
            }//end if
            else if (e.getActionCommand().equals(currentQues.getAnsD()))
            {
                String userAns = "D";
                checkAnswer(currentQues, userAns);
            }//end if
            else
                JOptionPane.showMessageDialog(null, "An error has occurred!", "ERROR!", JOptionPane.ERROR_MESSAGE);
        }//end method actionPerformed
    }//end class ButtonHandler
    
    public void checkAnswer(QuestionInfo currentQ, String uAnswer)
    {
        String correctAnswer = currentQ.getCorrectAns();
        if(correctAnswer.equals(uAnswer))
        {
            String ansMessage = "Correct!";
            score+= 100;
            JOptionPane.showMessageDialog(null, ansMessage, "Advanced Java Hangman", JOptionPane.PLAIN_MESSAGE);
        }//end if
        else
        {
            String ansMessage = "Incorrect!";
            numOfWrongAns++;
            JOptionPane.showMessageDialog(null, ansMessage, "Advanced Java Hangman", JOptionPane.PLAIN_MESSAGE);
        }//end else
        quizQuesNum++;
        AdvancedJavaHangman play = new AdvancedJavaHangman();
    }//end method checkAnswer
    
    public void displayQuestion(QuestionInfo[] questions, QuestionInfo cur_Ques, int quesNumber)
    {
        if((quizQuesNum < 10) && (numOfWrongAns < 3))
        {
            ImageIcon hangIcon = new ImageIcon();    
            if(numOfWrongAns == 0)
                hangIcon = new ImageIcon("Hangman0.jpg", "Hangman");
            else if(numOfWrongAns == 1)
                hangIcon = new ImageIcon("Hangman2.jpg", "Hangman");
            else if(numOfWrongAns == 2)
                hangIcon = new ImageIcon("Hangman3.jpg", "Hangman");
                    
                    setTitle("Advanced Java Hangman: Question " + (quizQuesNum + 1));
                    setSize(WIDTH, HEIGHT);
                    
                    Container pane = getContentPane();

                    pane.setLayout(null);
                    
                    ansButtonHandler = new ButtonHandler(cur_Ques);
                    
                    questionLabel = new JLabel(cur_Ques.getQuestion(), SwingConstants.CENTER);
                    questionLabel.setSize(580, 50);
                    questionLabel.setLocation(20, 520);
                    
                    hangLabel = new JLabel(hangIcon);
                    hangLabel.setSize(480, 480);
                    hangLabel.setLocation(100, 20);
                    
                    ansButtonA = new JButton(cur_Ques.getAnsA());
                    ansButtonA.setSize(200, 50);
                    ansButtonA.setLocation(200, 590);
                    ansButtonA.addActionListener(ansButtonHandler);
                    
                    ansButtonB = new JButton(cur_Ques.getAnsB());
                    ansButtonB.setSize(200, 50);
                    ansButtonB.setLocation(200, 660);
                    ansButtonB.addActionListener(ansButtonHandler);
        
                    ansButtonC = new JButton(cur_Ques.getAnsC());
                    ansButtonC.setSize(200, 50);
                    ansButtonC.setLocation(200, 730);
                    ansButtonC.addActionListener(ansButtonHandler);
                    
                    ansButtonD = new JButton(cur_Ques.getAnsD());
                    ansButtonD.setSize(200, 50);
                    ansButtonD.setLocation(200, 800);
                    ansButtonD.addActionListener(ansButtonHandler);
                    
                    exitButton = new JButton("Exit");
                    exitButton.setSize(75, 50);
                    exitButton.setLocation(263, 890);
                    exitButton.addActionListener(ansButtonHandler);
                    
                    pane.add(questionLabel);
                    pane.add(ansButtonA);
                    pane.add(ansButtonB);
                    pane.add(ansButtonC);
                    pane.add(ansButtonD);
                    pane.add(hangLabel);
                    pane.add(exitButton);
                    
                    setVisible(true);
                    setDefaultCloseOperation(EXIT_ON_CLOSE);
        }//end if
        else if((quizQuesNum == 10) && (numOfWrongAns < 3))
        {
            String gameOverStr = "You Win!\nYour score is " + score + ".";
            JOptionPane.showMessageDialog(null, gameOverStr, "Advanced Java Hangman: Game Over", JOptionPane.PLAIN_MESSAGE);
            System.exit(0);
        }
        else
        {
            String gameOverStr = "Sorry, You have three wrong answers!\nGame Over!\nYour total score is " + score + ".";
            
            JOptionPane.showMessageDialog(null, gameOverStr, "Advanced Java Hangman:  Game Over",
                                                    JOptionPane.PLAIN_MESSAGE);
                                setTitle("Advanced Java Hangman: Game Over ");
                    setSize(WIDTH, HEIGHT);
                    ImageIcon hangIcon = new ImageIcon("Hangman.jpg");
                    
                    Container pane = getContentPane();

                    pane.setLayout(null);
                    
                    ansButtonHandler = new ButtonHandler(cur_Ques);
                    
                    hangLabel = new JLabel(hangIcon);
                    hangLabel.setSize(480, 480);
                    hangLabel.setLocation(100, 20);
                                        
                    exitButton = new JButton("Exit");
                    exitButton.setSize(75, 50);
                    exitButton.setLocation(263, 890);
                    exitButton.addActionListener(ansButtonHandler);
                    
                    pane.add(hangLabel);
                    pane.add(exitButton);
                    
                    setVisible(true);
                    setDefaultCloseOperation(EXIT_ON_CLOSE);
        }//end else
    }//end method displayQuestion
    
    
        //class QuestionInfo defintion
public class QuestionInfo
{        
        //declare instance variables
    private String question;
    private String answerA;
    private String answerB;
    private String answerC;
    private String answerD;
    private String correctAnswer;
    private boolean isUnused;
    
        //default constructor
    public QuestionInfo()
    {
        setQuestionInfo("", "", "", "", "", "");
    }
    
        //constructor with parameters
    public QuestionInfo(QuestionInfo otherQues)
    {
        question = otherQues.question;
        answerA = otherQues.answerA;
        answerB = otherQues.answerB;
        answerC = otherQues.answerC;
        answerD = otherQues.answerD;
        correctAnswer = otherQues.correctAnswer;
        isUnused = otherQues.isUnused;
    }
        
        //constructor with parameters
    public QuestionInfo(String ques, String qAnsA, String qAnsB, String qAnsC, String qAnsD, String correctAns)
    {
        setQuestionInfo(ques, qAnsA, qAnsB, qAnsC, qAnsD, correctAns);
    }
    
        //method to set QuestioonInfo object
    public void setQuestionInfo(String ques, String qAnsA, String qAnsB, String qAnsC, String qAnsD, String correctAns)

    {
        question = ques;
        answerA = qAnsA;
        answerB = qAnsB;
        answerC = qAnsC;
        answerD = qAnsD;
        correctAnswer = correctAns;
        isUnused = true;
    }
        
        //method to get the question
    public String getQuestion()
    {
        return question;
    }
    
        //method to get answer A
    public String getAnsA()
    {
        return answerA;
    }
    
        //method to get answer B
    public String getAnsB()
    {
        return answerB;
    }
    
        //method to get answer C
    public String getAnsC()
    {
        return answerC;
    }
    
        //method to get answer D
    public String getAnsD()
    {
        return answerD;
    }
        
        //method to get the quesion's correct answer
    public String getCorrectAns()
    {
        return correctAnswer;
    }
    
        //method to find out if the question has been previously used
    public boolean getIsUnused()
    {
        return isUnused;
    }
    
        //method to change the value of isUnused to false
    public void changeToUsed()
    {
        isUnused = false;
    }
        
        //method to get a copy of the object
    public QuestionInfo getCopy()
    {
        QuestionInfo temp = new QuestionInfo();
            
        temp.question = question;
        temp.answerA = answerA;
        temp.answerB = answerB;
        temp.answerC = answerC;
        temp.answerD = answerD;
        temp.correctAnswer = correctAnswer;
        temp.isUnused = isUnused;
        
        return temp;
    }
}//end class QuestionInfo
    
    public static void displayRules()
    {
        String rulesStr = "Advanced Java Hangman!\n"
                    + "You will be asked a series of multiple choice questions from material\n"
                        + "covered in the Advanced Java course at Baker College.You win by answering\n"
                        + "at least 8 out of 10 questions correctly. Each time you answer a question \n"
                        + "incorrectly part of the hangman image appears. After three wrong answers,\n"
                        + "the entire image appears and you lose the game.\n"
                        + "Hope you studied!";
                        
        JOptionPane.showMessageDialog(null, rulesStr, "Advanced Java Hangman: Rules", JOptionPane.PLAIN_MESSAGE);
    }
    
    public int seqSearch(Vector<Integer> usedList, int questionNum)
    {
         boolean found = false;
        
         for (Integer num : usedList)
             if (num == questionNum)
              {
                  found = true;
                    break;
              }
         if (found)
             return 1;
              else
                 return -1;
    }
    
    public static void main(String[] args)
    {
        displayRules();
        
        AdvancedJavaHangman playGame = new AdvancedJavaHangman();
    }//end method main    
    


My file looks like so:
what is the logical primitive data type?
double
int
Boolean
String
C
What is the 16-bit Java character set?
char
Unicode
float
binary
B
Which method would you use to compare Strings?
getLength
compareString
countChar
compareTo
D
What class is used to develop a drop-down list?
JScrollPane
Component
abstract
JComboBox
D
What data type is actually tested in a While and Do-While loop?
double
Boolean
int
char
B
What is a dynamic way to implement a list in Java?
use the Vector class
use an array
use the List class
use an Object class
A
What sort technique always uses n-1 passes where n is the length of the list?
Sequential
list
bubble sort
binary
C
What is the superclass for applets?
Object
JApplet
JFrame
String
B
What is a unique instance of a class called?
wrapper class
superclass
Object
inheritance
C
What keyword is needed to derive a subclass from a superclass?
implements
instanceOf
extends
super
C
User is offlineProfile CardPM
+Quote Post

mensahero
RE: Vector Search
14 Jun, 2008 - 09:32 AM
Post #4

c0mput3rz Are Only Human
Group Icon

Joined: 26 May, 2008
Posts: 664



Thanked: 17 times
Dream Kudos: 75
My Contributions
I've done something similar to this one.

If you've done a class that will handle your question and answer. Then all you need to do is put a boolean variable that will return true if the question is already done or answered.
User is offlineProfile CardPM
+Quote Post

hezfast2
RE: Vector Search
14 Jun, 2008 - 09:45 AM
Post #5

New D.I.C Head
*

Joined: 19 May, 2008
Posts: 16

QUOTE(mensahero @ 14 Jun, 2008 - 10:32 AM) *

I've done something similar to this one.

If you've done a class that will handle your question and answer. Then all you need to do is put a boolean variable that will return true if the question is already done or answered.


My problem is that I need to use a search algorithm to do this for my project.
User is offlineProfile CardPM
+Quote Post

mensahero
RE: Vector Search
14 Jun, 2008 - 09:56 AM
Post #6

c0mput3rz Are Only Human
Group Icon

Joined: 26 May, 2008
Posts: 664



Thanked: 17 times
Dream Kudos: 75
My Contributions
QUOTE(hezfast2 @ 14 Jun, 2008 - 10:45 AM) *

My problem is that I need to use a search algorithm to do this for my project.


A search algorithm ?

Sorry but what is that?

whatever it is JAVA is OOP and Questions are OBJECTS so its a good practice to treat them as a CLASS.



User is offlineProfile CardPM
+Quote Post

hezfast2
RE: Vector Search
14 Jun, 2008 - 10:02 AM
Post #7

New D.I.C Head
*

Joined: 19 May, 2008
Posts: 16

QUOTE(mensahero @ 14 Jun, 2008 - 10:56 AM) *

QUOTE(hezfast2 @ 14 Jun, 2008 - 10:45 AM) *

My problem is that I need to use a search algorithm to do this for my project.


A search algorithm ?

Sorry but what is that?

whatever it is JAVA is OOP and Questions are OBJECTS so its a good practice to treat them as a CLASS.


I'm putting the question numbers in a vector list as the corresponding questions are asked. Every time a random question number is generated, a search is performed on the vector list to see if that number has been used, if it has, a new question number is generated, and so on. I just can't seem to be finding where it is not working.

This post has been edited by hezfast2: 14 Jun, 2008 - 10:03 AM
User is offlineProfile CardPM
+Quote Post

mensahero
RE: Vector Search
14 Jun, 2008 - 10:10 AM
Post #8

c0mput3rz Are Only Human
Group Icon

Joined: 26 May, 2008
Posts: 664



Thanked: 17 times
Dream Kudos: 75
My Contributions
CODE

questionNum = (int)(Math.random() * 10);
        isUsed = true;

        while (isUsed)
        {
            searchResult = seqSearch(usedList, questionNum);
            if (searchResult == -1)
            {
                isUsed = false;
            }
            else { << in your code. you forgot to add open bracket.
                questionNum = (int)(Math.random() * 10);
            }

        usedList.addElement(questionNum);

        QuestionInfo curQues = new QestionInfo(questionObj[questionNum]);
        displayQuestion(questionObj, curQues, questionNum);
        }  



Do you recieve any compile error? or any error?

if not. Then In my opinion the problem is in that code. See above.
If you read it line by line you'll see the problem.

This post has been edited by mensahero: 14 Jun, 2008 - 10:13 AM
User is offlineProfile CardPM
+Quote Post

gl3thr0
RE: Vector Search
14 Jun, 2008 - 10:21 AM
Post #9

D.I.C Head
**

Joined: 27 Oct, 2007
Posts: 209



Thanked: 3 times
My Contributions
okay well if i was 2 do this the first thing id do is change your text file around a little
make it look more like this

:what is the logical primitive data type?
*double
*int
*Boolean
*String
#3

:What is the 16-bit Java character set?
*char
*Unicode
*float
*binary
#2

.. and so on

then id write a search algorith that first looked for the ':' character then read the whole line after it into a string.
it then looked for the next four'*' charaters and read each of them into seperate strings and THEN looked for the next '#' character and read the number after it into a String. The program would then put all these values into a String array with the first string being the question, the next 4 answers the 5th the answer

when this finally finished you would have 10 different arrays with a question the answers and the correct answer. you would save all these into a MASTER array


User is offlineProfile CardPM
+Quote Post

mensahero
RE: Vector Search
14 Jun, 2008 - 10:23 AM
Post #10

c0mput3rz Are Only Human
Group Icon

Joined: 26 May, 2008
Posts: 664



Thanked: 17 times
Dream Kudos: 75
My Contributions
CODE

for (Integer num : usedList)
             if (num == questionNum)
              {
                  found = true;
                    break;
              }


are you required to use that kind of for loop? couldn't you use the standard for loop?
User is offlineProfile CardPM
+Quote Post

hezfast2
RE: Vector Search
14 Jun, 2008 - 10:42 AM
Post #11

New D.I.C Head
*

Joined: 19 May, 2008
Posts: 16

QUOTE(mensahero @ 14 Jun, 2008 - 11:23 AM) *

CODE

for (Integer num : usedList)
             if (num == questionNum)
              {
                  found = true;
                    break;
              }


are you required to use that kind of for loop? couldn't you use the standard for loop?


The braces are OK, no, I'm not getting any compiler errors. The weird looking for loop is because it is a vector list, not an array. I really don't know how, or if you can do it another way.

As per what you mentioned earlier? I've got a boolean variable 'isUnused' that I was playing around with earlier in the design, I'm not sure how I would implement it in the button handler so it would work though. This is giving me the crazies, I just found out that I need to get it posted TODAY for reviews (I originally thought it was Monday) Thanks for your help by the way
User is offlineProfile CardPM
+Quote Post

mensahero
RE: Vector Search
14 Jun, 2008 - 10:52 AM
Post #12

c0mput3rz Are Only Human
Group Icon

Joined: 26 May, 2008
Posts: 664



Thanked: 17 times
Dream Kudos: 75
My Contributions
CODE

usedList.addElement(questionNum);


Could you try.. moving that code outside the while loop.
Because if its inside your while loop the random number generated will automatically be added in your used list.

CODE

while (isUsed)
        {
        searchResult = seqSearch(usedList, questionNum);
        if (searchResult == -1)
        {
            isUsed = false;
      }//end if
        else
            questionNum = (int)(Math.random() * 10);
        usedList.addElement(questionNum);
        }//end while


try moving the "usedLIst.AddElement(questionNum)" outside of the while loop.

This post has been edited by mensahero: 14 Jun, 2008 -