I'm trying to make a java quiz linked to an sqlite database from where it's getting the informations (Questions and answers).
Every quiz has n questions.
A question has 4 options.
A question can have more than one true question.
so My database tables are:
Quiz(id_quiz, quiz_name)
Question (id_question, question, #id_quiz)
Answer (id_answer, statut, answer, #id_question)
So I created a first frame to select the quiz that we want to pass, it's working with a function that's calling the new Frame depending on the selected quiz.
My problem is when I compare the selected answers with the true answer that must be selected.
this is my code:
public boolean compare(List<Integer> trueAnswer, List<Integer> selected){
if (trueAnswer.equals(selected)){
return true;
} else {
return false;
}
}
The first step is to get the question in the jLabel, and the answers of that question too:
public List<Answer> showQuestion(int index){
in = fillQuestion(idQ).get(index).getIdQuestion();
jQuestion.setText(fillQuestion(idQ).get(index).getQuestion());
try {
con = DriverManager.getConnection("jdbc:sqlite:myflightdb.db", "", "");
String sql2 = ("select r.id_answer ,r.answer, r.statut from question q, answer r where q.id_question = ? and r.id_question = q.id_question ;");
PreparedStatement psmt2;
psmt2 = con.prepareStatement(sql2);
psmt2.setInt(1, in);
List<Answer> listRep = new ArrayList<Answer>();
rs2 = psmt2.executeQuery();
while(rs2.next()){
int idR = rs2.getInt("id_answer");
String rep = rs2.getString("answer");
String statut = rs2.getString("statut");
Reponse r = new Reponse(idR, rep, statut);
listRep.add(r);
}
return listRep;
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return null;
}
the function getTrueAnswer is made in order to get the list of true answers for question:
public List<Integer> getTrueAnswer(int index){
int idquestion;
idquestion = fillQuestion(idQ).get(index).getIdQuestion();
List<Integer> rep = new ArrayList<Integer>();
try {
con = DriverManager.getConnection("jdbc:sqlite:/Users/gate11/Desktop/MyFlight/myflightdb.db", "", "");
String sql = "select r.id_reponse from Reponse r where r.id_question = ? and r.statut like 'true';";
PreparedStatement psmt = con.prepareStatement(sql);
psmt = con.prepareStatement(sql);
psmt.setInt(1, idquestion);
rs = psmt.executeQuery();
while (rs.next()){
int idTrueAnswer= rs.getInt("id_reponse");
rep.add(idTrueAnswer);
}
//JOptionPane.showMessageDialog(null, Arrays.toString(rep.toArray()), "Selected IDs", JOptionPane.INFORMATION_MESSAGE);
return rep;
} catch (Exception e){
System.out.println(""+e.getMessage());
}
return null;
}
The button next must compare the selected jCheckBoxes with the true questions, if it's the same, the mark must be positif (so I can add the point to the result) or add 0 if the user doesn't choose the true one.
The problem is for the first time, it's working (I made the JOptionPanes to see the lists) so if I selected the first question, I have the selected is [1] and the true answer is [2]
but in the second question, if I select 1 I have the list is [1,1] for the third one [1,1,1] the fourth [1,1,1,1] etc ...
And I don't have any loop I can't find the problem.
If there is any idea please don't hesitate.
P.S: I did the 4 checkboxes because when I tried to add it in a for loop like that:
for (Answer a:listRep){
JcheckBox mycheck = new JcheckBox();
mycheck.setText(a.getQuestion());
mypanel.add(mycheck);
}
I found the problem, the itemListener must be added to the jCheckBoxes in the initialisation of the components.
Related
all,
I have an arraylist and I want to take the values one by one and put them in the string builder.
I have tried several steps, such as looping for and foreach
this is my code :
try{
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/"+jComboBox1.getSelectedItem()+"","root","");
Statement stmt=con.createStatement();
for(int i =0; i < box.size();i++){
if(box.get(i).isSelected()){
//System.out.print(box.get(i).getText().trim());
ResultSet rs=stmt.executeQuery("select "+box.get(i).getText().trim()+" from "+jComboBox3.getSelectedItem()+";");
while(rs.next()){
isikolom = rs.getString(1);
isi.add(isikolom);
String getkey = jTextField1.getText().toString();
byte[] key = getkey.getBytes();
RC4 rc = new RC4(new String(key));
byte[] desText = rc.decrypt(enText);
descrypted = new String(desText);
StringBuilder sb2 = new StringBuilder(128);
sb2.append("UPDATE ").append(jComboBox3.getSelectedItem().toString()).append(" SET ");
sb2.append(box.get(i).getText().toString()+" = ").append("REPLACE ").append("("+box.get(i).getText().toString()+",");
sb2.append("'"+isikolom+"'").append(",");
isideskripsi.stream().forEach(isideskripsi -> {
sb2.append("'"+isideskripsi+"'");
});
sb2.append(")");
String query2 = sb2.toString();
System.out.println(query2);
PreparedStatement presatet2 = con.prepareStatement(query2);
// presatet2.executeUpdate();
}
System.out.println("After Encryption : "+isiencrypsi);
System.out.println("After Descryption : "+isideskripsi);
}
}
end = System.currentTimeMillis();
long time = end - start;
JOptionPane.showMessageDialog(null, "Berhasil Deskripsi Dalam Waktu "+time+" Detik");
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Gagal Deskripsi, Error Pada : "+e);
System.out.print(e);
}
arraylist items is [admin, pegawai, penyidik]
this is result of that code :
UPDATE user SET username = REPLACE (username,'X"mBR','admin''pegawai''penyidik')
UPDATE user SET username = REPLACE (username,'I#gJK�','admin''pegawai''penyidik')
UPDATE user SET username = REPLACE (username,' I#nRU� �','admin''pegawai''penyidik')
the results i expected :
UPDATE user SET username = REPLACE (username,'X"mBR','admin')
UPDATE user SET username = REPLACE (username,'I#gJK�','pegawai')
UPDATE user SET username = REPLACE (username,' I#nRU� �','penyidik')
Because your description is not clear, I am not sure what you want to do is as follows:
int idx = 0;
while(rs.next()) {
...
sb2.append("'"+isikolom+"'").append(",");
/* remove this block
isideskripsi.stream().forEach(isideskripsi -> {
sb2.append("'"+isideskripsi+"'");
});
*/
sb2.append("'").append(isideskripsi.get(idx)).append("'");
sb2.append(")");
idx++;
...
}
isideskripsi.stream().forEach(isideskripsi -> {
sb2.append("'"+isideskripsi+"'");
});
The above code problems, because every time you build your SQL, you output all the items inside the arraylist, instead you should:
sb2.append("'"+isideskripsi.get(i-1)+"'");
As you only want every one arraylist item one time
I want to create a simple reservation application, like when you want to book movie ticket online, except this is a much simplified version.
I have a class names reservation with 8 toggle buttons and 1 button, the user will get to input number of seat they want to book in another class, let's just say 4.
In reservation, after the user choose 4 seats, the rest of the toggle button will be disabled to prevent user from choosing more seats. The user will then click the save button, and the data will then be inputted in the Database. Next time when another user open reservation, all of the toggle buttons will be re-enabled except those 4 seats previous user has booked earlier, obviously.
Everything is working so far except the part that i bold.
Here's my code :
private static final JToggleButton[] btn = new JToggleButton[8];
private int totalrow, a;
java.sql.Connection connection = null;
Statement statement4 = null;
ResultSet resultSet = null;
private void formWindowActivated(java.awt.event.WindowEvent evt) { // This is where i load the information that has been saved in the database before.
try {
connection = DriverManager.getConnection("jdbc:derby:
statement4 = (Statement) connection.createStatement();
resultSet = statement4.executeQuery("SELECT reservationid, seatno, validator FROM reservation WHERE reservationid = '" + time.id + "'");
String seatno, validator, rsid, id;
btn[0] = seat1;
btn[1] = seat2;
btn[2] = seat3;
btn[3] = seat4;
btn[4] = seat5;
btn[5] = seat6;
btn[6] = seat7;
btn[7] = seat8;
int i = 0;
while(resultSet.next()){
seatno = resultSet.getString("seatno");
validator = resultSet.getString("validator");
rsid = resultSet.getString("reservationid");
if(seatno.equals(btn[i].getText()) && validator.equals("reserved")){ //checking if seat i is reserved
btn[i].setSelected(true);
}
else{
btn[i].setSelected(false);
}
i++;
}
} catch (SQLException ex) {
Logger.getLogger(seat.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void actionPerformed(ActionEvent e) { // This actionlistener is used to count, if User has choose 4 seats, the code will disable the rest of the button
try {
connection = DriverManager.getConnection("jdbc:derby://localhost:1527/Project","root","root");
statement = (Statement) connection.createStatement();
btn[0] = seat1;
btn[1] = seat2;
btn[2] = seat3;
btn[3] = seat4;
btn[4] = seat5;
btn[5] = seat6;
btn[6] = seat7;
btn[7] = seat8;
a = 0;
for(JToggleButton btns : btn){
if (btns.isSelected()){
a++;
System.out.println(a);
if (! btns.isSelected()){
System.out.println(a);
a--;
}
}
}
for(JToggleButton btns : btn){
if (a >= Integer.parseInt(BookingUI.passenger)){ // This is number of Passenger taken from another class. In this case is 4.
if(! btns.isSelected()){
btns.setEnabled(false);
}
}
else{
btns.setEnabled(true);
}
}
} catch (SQLException ex) {
Logger.getLogger(seat.class.getName()).log(Level.SEVERE, null, ex);
}
}
Regarding my title, based on my current code and logic, it might not be possible to re-enable the toggle button. So the better way to do it might be to use another logic to disable the toggle button instead.
In the image, seat 1,4,5,8 are chosen by the user. And the rest of the buttons are disabled
Since it's a long implementation, it's difficult to answer with a code solution. There for I will mention my suggestion here.
You have to declare your JToggleButton Array like this btn = new JToggleButton[8]; in a public static context where every class could access it. And when the user reserved a seat you should save the data to DB (or keep in the program memroy, eg : HashMap) on which user reserved the which seat.
After that when you loading the data from the Database you should loop through and get the booked seats which previously inserted and then by accessing that predefined JToggleButton Array and set each booked seat by doing this btns[i].setEnabled(false); (i for the booked index of the seat).
Hope this helps
So I'm trying to make a save button to update the columns inside the database according to what's typed into their corresponding textfields, but I keep getting this error "Invalid operation at current cursor position". I can't figure out what's wrong since everything else is working. Can anyone help? Thanks in advance!
private void btn_saveActionPerformed(java.awt.event.ActionEvent evt) {
i = Integer.parseInt(txt_userid.getText( ));
s = txt_pass.getText( );
n = txt_name.getText( );
birthdate = txt_bdate.getText();
contactno = Integer.parseInt(txt_contact.getText());
age = Integer.parseInt(txt_age.getText());
email = txt_email.getText();
address = txt_address.getText();
gender = txt_gender.getText();
adult = Integer.parseInt(txt_adult.getText());
child = Integer.parseInt(txt_child.getText());
senior = Integer.parseInt(txt_senior.getText());
charge = Integer.parseInt(txt_charge.getText());
travelclass = txt_travelclass.getText();
luggage = txt_luggage.getText();
flightID = txt_flightid.getText();
departdate = txt_depardate.getText();
departtime = txt_departime.getText();
destination = txt_destination.getText();
arrivdate = txt_arrivdate.getText();
arrivtime = txt_arrivtime.getText();
try{
rs.updateInt("USERID",i);
rs.updateString("PASSWORD",s);
rs.updateString("USERNAME",n);
rs.updateInt("AGE",age);
rs.updateString("GENDER",gender);
rs.updateString("BIRTHDATE",birthdate);
rs.updateString("EMAIL",email);
rs.updateInt("CONTACTNO",contactno);
rs.updateString("ADDRESS",address);
rs.updateString("FLIGHTID", flightID);
rs.updateString("DEPARDATE", departdate);
rs.updateString("DEPARTIME", departtime);
rs.updateString("DESTINATION", destination);
rs.updateString("TRAVELCLASS", travelclass);
rs.updateString("LUGGAGE", luggage);
rs.updateInt("TOTALPAY", charge);
rs.updateInt("ADDPASSENGERSSENIOR", senior);
rs.updateInt("ADDPASSENGERSADULT", adult);
rs.updateInt("ADDPASSENGERSCHILD", child);
rs.updateString("ARRIVALDATE", arrivdate);
rs.updateString("ARRIVALTIME", arrivtime);
rs.updateRow( );
Refresh_RS_STMT();
ShowAll();
JOptionPane.showMessageDialog(AdminWindow.this,
"Record has been saved!");
}catch(SQLException err){
System.out.println(err.getMessage() );
}
}
Try to call the rs.next() before any usage of the ResultSet object. In fact a fresh ResultSet object have a pointer inside which points to -1 (none of the results by default), when you call the next() method for the first time it will point to the first row, if exists, and returns true, otherwise it will return false. each time you call it it will try to point to the next row and so on.
Good Day,
I've been working on an update in an android project, and came across an issue. I have to read questions from an SQLite database which i've done successfully by loading it into a multi-dimensional array as shown below in my database helper class:
public String getSome(int s,int t, String Table_Name){
String selectQuery = "SELECT * FROM " + Table_Name;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
int rows = cursor.getCount();
int num=0;
int col = 0;
String[][] base = new String[rows][13];
if (cursor.moveToFirst()) {
do {
for (col=0;col<13;++col ){
base[num][col] = (cursor.getString(col));}
++num;
} while (cursor.moveToNext());
return base[s][t];
}
return null;
}
With that done, i read the questions as such in my question class:
public void database_calls(){
setCourseTag(courseTag);
myDbHelper = new DataBaseHelper(getActivity());
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
String no= myDbHelper.getSome(ques,0, getCourseTag());
String qu = myDbHelper.getSome(ques,1, getCourseTag());
String a = myDbHelper.getSome(ques,2, getCourseTag());
String b = myDbHelper.getSome(ques,3, getCourseTag());
String c = myDbHelper.getSome(ques,4, getCourseTag());
String d = myDbHelper.getSome(ques,5, getCourseTag());
ans = myDbHelper.getSome(ques,6, getCourseTag());
img = Integer.parseInt(myDbHelper.getSome(ques,8, getCourseTag()));
exp = myDbHelper.getSome(ques,9, getCourseTag());
year = myDbHelper.getSome(ques,10, getCourseTag());
questionImage = myDbHelper.getSome(ques,11, getCourseTag());
length = myDbHelper.getMax(getCourseTag());
}
So recently, i tried to use the year column, (i.e, column 10) to qualify the questions chosen for each quiz session, so that the user may be able to select the questions from any year, he/she wants to attempt. In order to do this, i used a loop at the beginning of the activity to filter out only the required year past questions. Then i transferred the indices of each question to a set, bal , from where it is iterated and so on..
public void countYearQuestions(){
for(int y = 0; y < length; ++y){
//year = myDbHelper.getSome(y,10, getCourseTag());
if (selectedYear.equals(myDbHelper.getSome(y,10, getCourseTag())))
bal.add(y);
}
}
Here, length is the size of the entire question database, for the course, (indicated by getCourseTag()). The code works quite alright. But it takes a whole 8-9secs!! for the activity to load. Any help on how to reduce this loading time would be appreciated.
The way you're doing this is pretty efficient in slowing everything down (and your helper helps you with it a lot):
String no= myDbHelper.getSome(ques,0, getCourseTag());
In each such line you execute a query, create a 2D array holding the whole table and throw nearly everything away. And you fail to close the Cursor.
So you need 12 values from a table and read instead the whole table 12 times.
I have a pretty introductory question that I hope can get answered rather easily.
Currently I am trying to write something that queries my DB, returns result set (list of account id's) and then sets those account id's into an array so that I can populate an object with the values.
My object is going to be used as input into another method I have written but I can't figure out how I go about populating my account_id field on it with the values in my array that I returned in the result set. There doesn't seem to be any "setter" methods for lack of a better term on my array of type String.
I was able to get the array to populate with acct_id's from the result set and print them out so I know that I do have information coming back.
Below is the snippet I currently have, any help/improvements I could make would be greatly appreciated!
try {
connection = DriverManager.getConnection(url, user, password);
st = connection.createStatement();
rs = st.executeQuery(sql);
List<Long> array = new ArrayList<Long>();
while (rs.next()) {
array.add((long) rs.getLong("acct_id"));
for (Integer i = 0; i < array.size(); i++) {
System.out.println(array.get(i));
GetSummaryRequest request = new GetSummaryRequest();
request.accountKey = new AccountDTO(array[i]);
}
}
} catch (SQLException e) {
System.out.println("Connection failed.");
e.printStackTrace();
return;
}
if (rs.next()) {
System.out.println(rs.getString(1));
} else
System.out.print("Failed. Try again");
}
If my understanding is correct you may need the code below which is used to store all the account id's inside an array and you can use this to pass as a parameter to another method.
ArrayList<GetSummaryRequest> array1=new ArrayList<GetSummaryRequest>();
GetSummaryRequest request = new GetSummaryRequest();
while (rs.next())
{
request=new GetSummaryRequest();
request.accountKey=rs.getString("acct_id");
array1.add(request);
}
Now you have ArrayList of GetSummaryRequest with accountKey for each object.
if i understand correctly accountkey is integer right?
you can use Integer.parseint('your string!') class to convert the string to int.
i hope it helps
First of all , storing newline separated values in one column is not a good practice. This is against atomicity principle and will lead you to problems soon - ex., total number of accounts? how do you find it?
Once you convince yourself with this, you can use only one loop like this
List<GetSummaryRequest> summaryRequests = new ArrayList<GetSummaryRequest>();
while (rs.next()) {
String em = rs.getString("acct_id");
GetSummaryRequest request = new GetSummaryRequest();
request.accountKey = em;
summaryRequests.add(request);
}
return summaryRequests;
Probably you need something like that:
// First you get all ids
List<String> accountsIds = new ArrayList<String>();
while (rs.next()) {
accountsIds.add(rs.getString("acct_id"));
}
// Then iterate ids
for (String id : accountsIds) {
GetSummaryRequest request = new GetSummaryRequest();
request.accountKey = id;
}