Results 1 to 20 of 26
Thread: Array within Array
- 03-02-2011, 05:16 AM #1
Member
- Join Date
- Mar 2011
- Posts
- 12
- Rep Power
- 0
Array within Array
Hi all,
I just want to ask some help in my program. Actually I'm having a difficulty using array in java. The is about a quiz program. When a student select an answer using check box, there is an equivalent point of the answer. Like this one:
static String []questions = {"Question 1:\nWhat is the chemical symbol for Lead?","Question 2: \nHallux is another term for what part if the body?", "Question 3:\nThermodynamics is the study of heat energy and ______.","Question 4:\nNeon, helium, krypton, xenon, radon are what kind of gases?","Question 5:\nWhat is the male part of the flower?"};
static String [][]answers = {{"Pb","W","Ld","L"},{"Thumb","Big Toe","Middle Finger","Small Toe"}, {"Wind","Work","Water","Land"},{"Laughing Gases","Noble Gases","Natural Gases","Petrolium Gases"},{"Ovule","Stamen","Stigma","Sepal"}};
static String [][]point = {{"20","15","10","5"},{"5","20","15","10"},{"10"," 20","5","15"},{"15","20","10","5"},{"10","20","5", "15"}};
So, for question 1, every letter of choice has an equivalent points. After finish answering the five questions, the student automatically see the result.
I really need your help.
Thanks...
-
- 03-02-2011, 05:20 AM #3
Sure. As soon as you ask a question someone will be willing to answer it.
- 03-02-2011, 05:21 AM #4
Member
- Join Date
- Mar 2011
- Posts
- 12
- Rep Power
- 0
My problem is how to obtain the equivalent points to each letter of choice.
-
- 03-02-2011, 05:23 AM #6
By the way, parallel arrays are evil. It would be better if you wrote a class to encapsulate all the data. Then you can write methods that can help achieve your goals.
- 03-02-2011, 05:30 AM #7
Member
- Join Date
- Mar 2011
- Posts
- 12
- Rep Power
- 0
I'm done with the GUI and other stuff, I'm only stuck with this array. I think I'm lost. If I assign a correct answer to each question, I can get how much correct answers do u have. But with the point system, I'm lost with my array.
- 03-02-2011, 05:49 AM #8
So you are ignoring my advice. Good luck.
- 03-02-2011, 05:54 AM #9
Member
- Join Date
- Mar 2011
- Posts
- 12
- Rep Power
- 0
Thanks, I'm trying my best to do what you've advice. I'm still lost with my coding. I'm a newbee to this language. Can you please give me a pseudo code for that?
- 03-02-2011, 06:06 AM #10
Java Code:class Question { array of Answer objects String of real answer method to compare user choice to real answer other methods } class Answer { String of choice int for point value method to return choice method to return point value other methods }
- 03-02-2011, 06:14 AM #11
Member
- Join Date
- Mar 2011
- Posts
- 12
- Rep Power
- 0
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class QuestionData {
static String info ="There are 5 questions in this Trivia Game.\nWhen you are on the last question the Finish button will be highlighted in Cyan.\nWhen you click on Finish, you will get the result immediately.\n\nTo proceed, click 'Start'. \n\nGood Luck!!! ";
static String []questions = {"Question 1:\nWhat is the chemical symbol for Lead?",
"Question 2: \nHallux is another term for what part if the body?",
"Question 3:\nThermodynamics is the study of heat energy and ______.",
"Question 4:\nNeon, helium, krypton, xenon, radon are what kind of gases?",
"Question 5:\nWhat is the male part of the flower?"};
static String [][]answers = {{"Pb","W","Ld","L"},{"Thumb","Big Toe","Middle Finger","Small Toe"},
{"Wind","Work","Water","Land"},{"Laughing Gases","Noble Gases","Natural Gases","Petrolium Gases"},
{"Ovule","Stamen","Stigma","Sepal"}};
static String [][]point = {{"20","15","10","5"},{"5","20","15","10"},{"10"," 20","5","15"},
{"15","20","10","5"},{"10","20","5","15"}};
static int []n = {1,1,1,1,1}; //number of selection
static String []c = {"1","2","2","2","2"}; //correct answers
static String title = ".::Welcome to Trivia Game::.";
static int tally = c.length;
static int pointTally = point.length;
static int passMark = 50;
}
This is the class I made for the initializations. Then I call the QuestionData class in my Quiz class. I'll just provide you the whole code. I hope you will help in solving my problem.
Thanks,
Quiz.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Quiz extends JFrame {
static String name="";
static int TOTAL=0;
static int TOTAL_POINTS=0;
static {
try {
TOTAL = QuestionData.tally;
TOTAL_POINTS = QuestionData.pointTally;
if(TOTAL==0){
JOptionPane.showMessageDialog(null,"<html>No question found in the system.</html>","Program Exit",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
else name = JOptionPane.showInputDialog("Enter your name below");
if(name.length() < 1) name = " noname.java";
else name = name.trim() + " ";
}catch(NullPointerException e){System.exit(0);};
}
JLabel student, choose, message, timer, result, theQ;
int seconds, minutes, qCount, itemCheck, mark, points;
final String TITLE = QuestionData.title;
boolean startTheTest, checkAnswers, allowRestart, finishAll;
final int PASSMARK = QuestionData.passMark;
String []answers = new String[TOTAL];
String []x_points = new String[TOTAL_POINTS];
JButton []butt = new JButton[6];
JTextPane pane = new JTextPane();
JCheckBox []boxes = new JCheckBox[4];
JTextArea answerTA[] = new JTextArea[4];
PanelNorth panelNorth = new PanelNorth();
PanelSouth panelSouth = new PanelSouth();
PanelCenter panelCenter = new PanelCenter();
protected Quiz() {
for(int i=0; i<TOTAL; i++) answers[i] = "";
getContentPane().setLayout(new BorderLayout());
getContentPane().add("North", panelNorth);
getContentPane().add("South", panelSouth);
getContentPane().add("Center", panelCenter);
int width = 0, height = 0;
if(java.awt.Toolkit.getDefaultToolkit().getScreenS ize().getWidth()<799){width=640; height=460;}
else {width=720; height=540;}
setSize(width, height);
Dimension dim = java.awt.Toolkit.getDefaultToolkit().getScreenSize ();
setLocation((dim.width-width)/2, (dim.height-height)/2);
}
class PanelNorth extends JPanel {
public PanelNorth() {
setLayout(new GridLayout(2,2));
student = new JLabel(" Student: "+name);
message = new JLabel();
message.setForeground(Color.blue);
add(student);
add(message);
add(new JLabel(" Questions") );
add(new JLabel(" Answers") );
setBorder(BorderFactory.createEtchedBorder() );
}
}
class PanelSouth extends JPanel {
public PanelSouth() {
setBackground(new Color(230, 230, 255));
String []labs = {"Explain","Start","Previous","Next","Finish","Res tart"};
for(int i=0; i<butt.length; i++) {
butt[i] = new JButton(labs[i]);
butt[i].addActionListener(new ActionHandler());
if(i !=0)add(butt[i]);
}
setBorder(BorderFactory.createEtchedBorder());
}
}
class PanelCenter extends JPanel {
public PanelCenter() {
setLayout(new GridLayout(1,2));
JScrollPane west = new JScrollPane(pane);
pane.setFont(new Font("monospaced",0,12));
pane.setText(QuestionData.info);
pane.setEditable(false);
JPanel east = new JPanel();
east.setLayout(new BorderLayout());
JPanel northEast = new JPanel();
northEast.setBackground(new Color(230,230,255));
east.add("North", northEast);
JPanel westEast = new JPanel();
westEast.setLayout(new GridLayout(6,1));
east.add("West", westEast);
JPanel centerEast = new JPanel();
centerEast.setLayout(new GridLayout(6,1));
centerEast.setBackground(new Color(255,255,200));
east.add("Center", centerEast);
timer = new JLabel(" There are "+TOTAL+" questions in total.");
timer.setFont(new Font("Arial", Font.BOLD, 16));
timer.setForeground(new Color(0,90,20));
northEast.add(timer);
theQ = new JLabel();
theQ.setFont(new Font("",Font.BOLD,16) );
westEast.add(theQ);
String []boxs = {" A ", " B ", " C ", " D "};
for(int i=0; i<boxes.length; i++) {
boxes[i] = new JCheckBox(boxs[i]);
boxes[i].addItemListener(new ItemHandler() );
westEast.add(boxes[i]);
}
westEast.add(new JLabel() );
choose = new JLabel(" CHOOSE YOUR ANSWER ON THE CHOICES BELOW");
choose.setBorder(BorderFactory.createEtchedBorder( ) );
centerEast.add(choose);
JScrollPane panes[] = new JScrollPane[4];
for(int i=0; i<answerTA.length; i++){
answerTA[i] = new JTextArea();
answerTA[i].setBorder(BorderFactory.createEtchedBorder() );
answerTA[i].setEditable(false);
answerTA[i].setBackground(Color.white);
answerTA[i].setFont(new Font("",0,12) );
answerTA[i].setLineWrap(true);
answerTA[i].setWrapStyleWord(true);
panes[i] = new JScrollPane(answerTA[i]);
centerEast.add(panes[i]);
}
result = new JLabel("");
result.setBorder(BorderFactory.createEtchedBorder( ) );
centerEast.add(result);
add(west);
add(east);
}
}
class ActionHandler implements ActionListener {
public void actionPerformed(ActionEvent evt) {
String source = evt.getActionCommand();
if(source.equals("Start")) {
startTheTest = true;
allowRestart = true;
butt[1].setVisible(false);
panelSouth.remove(butt[1]);
getQuestion();
}
if(startTheTest) {
if(source.equals("Previous")) {
recordAnswer();
qCount--;
if(qCount == -1) qCount=TOTAL-1;
checkStatus();
getQuestion();
}
if(source.equals("Next")) {
recordAnswer();
qCount++;
if(qCount == TOTAL-1) finishAll=true;
if(qCount == TOTAL) qCount=0;
checkStatus();
getQuestion();
}
if(source.equals("Finish")) {
if(finishAll) {
recordAnswer();
qCount = 0;
butt[4].setBackground(Color.lightGray);
startTheTest = false;
checkAnswers = true;
colorTA();
getQuestion();
checkStatus();
calculateResult();
for(int i=0; i<boxes.length; i++) boxes[i].setSelected(false);
}
else JOptionPane.showMessageDialog(null,"Cycle through questions before pressing Finish","User Message",JOptionPane.INFORMATION_MESSAGE);
}
}//end startTheTest
if(allowRestart){
if(source.equals("Restart")){
if(startTheTest)
seconds= minutes= qCount=0;
checkAnswers=false;
for(int i=0; i<TOTAL; i++) answers[i]="";
for(int i=0; i<boxes.length; i++) boxes[i].setSelected(false);
for(int i=0; i<answerTA.length; i++) answerTA[i].setBackground(Color.white);
choose.setText(" CHOOSE ONE CORRECT ANSWER");
result.setText("");
getQuestion();
startTheTest=true;
}
}//end allowRestart
validate();
}//end actionPerformed
}//end ActionHandler
class Results extends JFrame{
Results() {
super("Results: " +(mark*100/TOTAL >=PASSMARK?"PASS":"FAIL") );
if(mark*100/TOTAL >=PASSMARK)this.setIconImage(Toolkit.getDefaultToo lkit().getImage(Quiz.class.getResource("pass.gif") ));
else this.setIconImage(Toolkit.getDefaultToolkit().getI mage(Quiz.class.getResource("fail.gif")));
Container cont = getContentPane();
cont.setLayout(new GridLayout(TOTAL/2+3,5,2,5) );
cont.setBackground(new Color(225,220,255) );
cont.add(new JLabel(" "+name+" "+mark+"/"+TOTAL+": "+(mark*100/TOTAL)+"%") );
for(int i=0; i<3; i++)cont.add(new JLabel() );
String temp[] = new String[TOTAL];
for(int i=0; i<TOTAL; i++){
if(QuestionData.c[i].equals(answers[i])) temp[i]="Correct";
else temp[i]="Wrong";
}
for(int i=0; i<TOTAL; i++) cont.add(new JLabel(" Question "+(i+1)+": "+temp[i]) );
pack();
setLocation(200,200);
}
}
public void calculateResult(){
mark=0;
double temp=0.0;
java.text.DecimalFormat df = new java.text.DecimalFormat("#0.#");
for(int i=0; i<TOTAL; i++)if(QuestionData.c[i].equals(answers[i]))mark++;
temp=(double)mark;
if(temp/TOTAL_POINTS*100 >=PASSMARK) result.setText(" Well done "+name.substring(0,name.indexOf(' ') )+", you passed");
else result.setText(" Better luck next time "+name.substring(0,name.indexOf(' ') ) );
student.setText(" Final score for "+name+": "+mark+" out of "+TOTAL+": "+df.format(temp/TOTAL*100)+"%");
new Results().show();
}
public void checkStatus(){
if((qCount == TOTAL-1)&&(startTheTest))butt[4].setBackground(Color.cyan);
else butt[4].setBackground(Color.lightGray);
if(answers[qCount].length() >0){
for(int i=0; i<answers[qCount].length(); i++)
boxes[Integer.parseInt(answers[qCount].substring(i,i+1) )-1].setSelected(true);
}
else for(int i=0; i<boxes.length; i++)boxes[i].setSelected(false);
}
public void recordAnswer(){
String tmp = "";
for(int i=0; i<boxes.length; i++) {
if(boxes[i].isSelected() ) tmp +=i+1;
answers[qCount] = tmp;
//x_points[qCount] = tmp;
}
System.out.print(tmp);
for (int x=0; x<x_points; x++) {
}
}
public void getQuestion() {
int j = qCount+1;
theQ.setText(" Q"+j+":");
pane.setText(QuestionData.questions[qCount]);
if(startTheTest)message.setText("Question "+j+" out of "+TOTAL);
for(int i=0; i<4; i++)answerTA[i].setText(QuestionData.answers[qCount][i]);
if(startTheTest) {
String temp="";
if(QuestionData.n[qCount]==1) temp="<html> CHOOSE YOUR ANSWER ON THE CHOICES BELOW</html>";
else temp="<html> Please select an answer for this question.</html>";
choose.setText(temp);
}
}
public void colorTA(){
for(int i=0; i<answerTA.length; i++) answerTA[i].setBackground(Color.white);
if(QuestionData.c[qCount].equals(answers[qCount])) message.setText("Answer correct, well done!");
}
public void doAlert(){
timer.setForeground(Color.red);
java.awt.Toolkit.getDefaultToolkit().beep();
validate();
}
public void endTest(){
butt[2].setEnabled(false);
butt[3].setEnabled(false);
butt[4].setEnabled(true);
}
class ItemHandler implements ItemListener{
public void itemStateChanged(ItemEvent evt){
if(startTheTest){
for(int i=0; i<boxes.length; i++) if(boxes[i].isSelected() ) itemCheck++;
if(itemCheck > QuestionData.n[qCount]){
java.awt.Toolkit.getDefaultToolkit().beep();
if(QuestionData.n[qCount]==1) JOptionPane.showMessageDialog(null,"<html><font size='4' color='00308a'><center>"+
"There is only "+QuestionData.n[qCount]+" possible<br> answer to Question "+(qCount+1)+"."+
"<html>","User Information Message",JOptionPane.INFORMATION_MESSAGE);
else JOptionPane.showMessageDialog(null,"<html><font size='4' color='00308a'><center>"+
"There are only "+QuestionData.n[qCount]+" possible<br> answers to question "+(qCount+1)+
"<html>","User Information Message",JOptionPane.INFORMATION_MESSAGE);
}
itemCheck=0;
}
}
}
public static void main(String args[]) {
Quiz frame = new Quiz();
frame.setTitle(" " + QuestionData.title);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
- 03-02-2011, 06:25 AM #12
Senior Member
- Join Date
- Jan 2011
- Location
- Bangalore, India
- Posts
- 102
- Rep Power
- 0
Make use of HashTable
Create a new class as shown below. Now In your old class, call the getPoints method by passing the question number and choice as arguments. That's it.Java Code:public class PointsTable { private String[][][] pointsTable = { { {"Pb","20"}, {"W","15"}, {"Ld","10"}, {"L","5"}, }, { {"Thumb","5"}, {"Big Toe","20"}, {"Middle Finger","15"}, {"Small Toe","10"}, }[I][COLOR="YellowGreen"]//create the rest yourself[/COLOR][/I] }; private Hashtable<String, Integer> hTable = new Hashtable<String, Integer>(); private Hashtable<String, Integer> hashTableCreator(int question) { String[][] subTable = pointsTable[question-1]; for (int i=0; i<subTable.length; i++) { hTable.put(subTable[i][0], Integer.parseInt(subTable[i][1])); } return hTable; } public int getPoints(int question, String choice) { return hashTableCreator(question).get(choice); } }
This worked for me. This is just a sample and please don't copy paste. Learn Hashtable and understand the concept before going forward.
The only thing I don't agree with this solution is hardcoding private String[][][] pointsTable. In future you introduce a 5th question. Then you need to change this class and build again, which is not a good design. Please find out an alternate way to this problem yourself (though this will definitely work)
- 03-02-2011, 06:31 AM #13
Member
- Join Date
- Mar 2011
- Posts
- 12
- Rep Power
- 0
Thanks, but I still have to study using Hash table. I really don't know on how to use hash table. I still have to figure it out and understand it for my reference.
- 03-02-2011, 06:38 AM #14
Senior Member
- Join Date
- Jan 2011
- Location
- Bangalore, India
- Posts
- 102
- Rep Power
- 0
- 03-02-2011, 06:53 AM #15
Member
- Join Date
- Mar 2011
- Posts
- 12
- Rep Power
- 0
Actually, I cannot call myself a Java programmer. I'm still learning this language myself, I may be right or wrong for choosing this language as my preference and right now, I'm in a difficult moment with this language. Hopefully to overcome this in the coming days....
- 03-02-2011, 07:03 AM #16
Senior Member
- Join Date
- Jan 2011
- Location
- Bangalore, India
- Posts
- 102
- Rep Power
- 0
I just got a better solution. Keep this for your later reference.
Java Code:public class PointsTable { private String[][][] pointsTable = { { {"Pb","20"}, {"W","15"}, {"Ld","10"}, {"L","5"}, }, { {"Thumb","5"}, {"Big Toe","20"}, {"Middle Finger","15"}, {"Small Toe","10"}, } }; private ArrayList<Hashtable<String, Integer>> ptsList = new ArrayList<Hashtable<String, Integer>>(); public int getPoints(int question, String choice) { return ptsList.get(question-1).get(choice); } PointsTable() { Hashtable<String, Integer> hTable = new Hashtable<String, Integer>(); for (String[][] subArray : pointsTable) { for(String[] subString : subArray) { hTable.put(subString[0], Integer.parseInt(subString[1])); } ptsList.add(hTable); } } }
- 03-02-2011, 07:09 AM #17
Member
- Join Date
- Mar 2011
- Posts
- 12
- Rep Power
- 0
Thanks, I just keep this sample class. Is it okay to have sample of running application for the class you created above?. Just for my reference, I'm really lost with this application. Please....
- 03-02-2011, 07:27 AM #18
Senior Member
- Join Date
- Jan 2011
- Location
- Bangalore, India
- Posts
- 102
- Rep Power
- 0
- 03-02-2011, 07:55 AM #19
Member
- Join Date
- Mar 2011
- Posts
- 12
- Rep Power
- 0
I'm lost in implementing the class in my program.....
- 03-02-2011, 09:04 AM #20
Senior Member
- Join Date
- Jan 2011
- Location
- Bangalore, India
- Posts
- 102
- Rep Power
- 0
Similar Threads
-
convert byte array into char array
By kgkamaraj in forum New To JavaReplies: 4Last Post: 09-13-2011, 11:32 AM -
Variable of an object in an array compared to an element of another array?
By asmodean in forum New To JavaReplies: 23Last Post: 09-07-2010, 08:12 PM -
Trying to make an array list // inserting an element to middle of array
By javanew in forum New To JavaReplies: 2Last Post: 09-06-2010, 01:03 AM -
Convert Char Array to String Array
By Mayur in forum New To JavaReplies: 8Last Post: 10-12-2009, 11:41 AM -
How to add an integer to a array element and the store that backinto an array.
By Hannguoi in forum New To JavaReplies: 1Last Post: 03-31-2009, 06:40 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks