I'm making a simple quiz program. I need to display my Correct and Wrong it depends on the answer of the user. I think it is in the IF else. That's why I can't get it through. When I run it. I choose the correct answer. It is still displaying "Wrong!" and it counts it as correct. and Then change to different number. It is still displaying "Wrong!". I'm using checkbox as the multiple choice of the quiz.
Here's my code:
if(C1.getState()) // if the user chooses the checkbox c1
{
outputlabel.setText("Correct\n");
CorrectAnswer++; // it will count one point per correct answer.
}else
outputlabel.setText("Wrong!\n");
if(C13.getState()) // if the user chooses the checkbox C13
{
outputlabel.setText("Correct\n");
CorrectAnswer++;
}else
outputlabel.setText("Wrong!\n");
if(C19.getState()) // if the user chooses the checkbox C19
{
outputlabel.setText("Correct\n");
CorrectAnswer++;
}else
outputlabel.setText("Wrong!\n");
if(C21.getState()) // if the user chooses the checkbox C21
{
outputlabel.setText("Correct\n");
CorrectAnswer++;
}else
outputlabel.setText("Wrong!\n");
if(C27.getState()) // if the user chooses the checkbox C27
{
outputlabel.setText("Correct\n");
CorrectAnswer++;
}else
outputlabel.setText("Wrong!\n");
CorrectLabel.setText("Correct Answers: "+CorrectAnswer);
score =(CorrectAnswer*100)/5; // average of the quiz
if (score>=75)
{
scorelabel.setText("Grade: "+score+ "% ");
}else{
scorelabel.setText("Grade: "+score+"%.");
repaint();}
}
}
I'm not entirely sure what you're trying to do in the code. For each you're checking if it is set, and then you're setting the outputlabel value. So if the first checkbox is checked it will set the outputlabel text to "Correct". And if any of the other checkboxes are not checked it will then simply override what you did before and set the label to "Wrong".
Maybe you want separate outputlabels for each of the checkboxes?
You should have one final output label, after you check the state of all the correct answers. And based on the correct answers count, you can set the final output label.
Related
I believe I have encountered a bug within the JavaFX API, but I'm not sure. So the following snippet behaves normally, but when I add an alert.show(); or alert.showAndWait();, the program opens three different alert dialogues. Here's the code:
private void datePickerOnHiding(JFXDatePicker datePicker, JFXCheckBox chkBox) {
int counter = 0;
boolean entered = false;
if (datePicker.getValue().isBefore(LocalDate.now()) ||datePicker.getValue().isEqual(LocalDate.now())) {
if ((eventHiddenCounter % 2) == 0) {
System.out.println("HAHA");//Testing
txtfMessage.setVisible(true);
txtfMessage.setText("Please select a future date.");
Alert alert = new Alert(AlertType.WARNING, "Please select a future date.");
alert.showAndWait();
datePicker.setValue(null);
counter ++;
entered = true;
}
} else {
txtfMessage.setVisible(false);
chkBox.setSelected(true);
}
//Testing
System.out.println("" + eventHiddenCounter + ": " + ((eventHiddenCounter % 2) == 0));
System.out.println("COUNTER: " + counter + "\nENTERED: " + entered);
entered = false;
eventHiddenCounter ++;
}
Here's the ouput with the alert.showAndWait commented out:
HAHA
0: true
COUNTER: 1
ENTERED: true
Here it is with it included (the bug):
HAHA
HAHA
HAHA
0: true
COUNTER: 1
ENTERED: true
1: false
COUNTER: 1
ENTERED: true
2: true
COUNTER: 1
ENTERED: true
I am quite perplexed--why is this happening, and what can I do to get around it?
By the way, the goal is to prevent the user from picking a date equal to or before the current day.
The date picker creates a popup and your alert is also a popup window.
The most likely reason (I can't be sure because I have no idea how datePickerOnHiding() is being called) is that the two popups are having race condition. When you try to show the alert, you are triggering the datePickerOnHiding() because it is trying to hide again.
If you want to stop user from selecting invalid values, you need to trigger this method after the datepicker popup is already closed (i.e. hidden).
Jai's answer is helpful, but I just disabled the days I didn't want using DayCells.
See:
http://o7planning.org/en/11085/javafx-datepicker-tutorial
javafx datepicker how to customize
I used the first one.
Edit: I figured out what was causing the repetition.
The focus shifts in the scene after the Alert dialogue is closed in the closing event listener. I have a similar (read: same) dialogue for a focus-lost listener (they fire under the same conditions), so the dialogues appeared to be the same, despite having different origins. Essentially, the focus kept oscillating to and from the node with the focus listener, causing numerous Alert popups for one error.
I realized my mistake after changing the AlertType of the closing listener Alert.
Simple fix - I made an externalRequest boolean flag, and I changed the focusListener event handler to do nothing if the externalRequest flag was true. Worked like a charm.
I am creating a mobile application that updates users with the current score and final score in a football match. I want the textview displaying the score to show only the current or final score.
I am having trouble with the if statement. I need one of the fields to contains something in order for a record to be created so I have:
if (!(et_currentgoals.getText().toString().isEmpty()) || !(et_finalgoals.getText().toString().isEmpty()){
}
Inside this if statement I was another that updates the textview with the correct values. So if the final number of goals was entered, the current goals are discarded. Would the best way be something like this:
if(!(et_finalgoals.getText().toString.isEmpty()){
tv_goals.setText(et_finalgoals.getText().toString();
}else{
tv_goals.setText(et_currentgoals.getText().toString();
}
Does this cover both scenarios or am I missing something?
Having that second if block inside the first will work, but there's a simpler way.
This single if will work.
if (!et_finalgoals.getText().toString.isEmpty()) {
tv_goals.setText(et_finalgoals.getText().toString();
} else if (!et_currentgoals.getText().toString.isEmpty()) {
tv_goals.setText(et_currentgoals.getText().toString();
}
In other words, these two blocks are equivalent
if (a || b) {
if (a) {
// a
} else {
// b
}
}
if (a) {
// a
} else if (b) {
// b
}
If I'm understanding correctly, you are executing additional code inside of that first if statement, after setting the tv_goals text. To do that now, you can just check the text of tv_goals.
if (!tv_goals.getText().toString.isEmpty()) {
// Do additional code
}
If this is the case, it ends up being the same amount of code as your original solution. You should just pick whichever way is more clear to you.
In my app, I need for values from buttons (the value is taken from an SQLite database) to be displayed in one of 13 JTextFields, and they can be in any order. How do I make it possible for the value to be displayed in the next available JTextField, if say the first one is empty?
The only thing I could think of was
if (textField.getText().isEmpty())
{
String text = String.valueOf(num);
textField.setText(textField.getText() + text);
}
What should I do next? How should I go around the else statement? Should I even use it?
Thanks in advance!
If I understand your question correctly,this should be the idea
JTextField[] fields = new JTextField[13];
firstText.setName("First Text") ;
.......
field[0] = firstText;
field[1] = SecondText;
//then add remaining textfields
for(JTextField txtField : fields) {
if(txtField.getText().equals("") ) {
// do whatever you want
}else{
// do whatever you want
}
}
So I am very new to this and I am trying to get the variables to add up during the process of the code in order to print the total at the end, in doing so, I need it to read the selection from the JOptionPane that the user entered and add the value to the total at the end. The code is almost complete but is missing the calculation of the variables.
Q: How do I get the value of any variable based on what the user selects from the JOptionPane and add it to the cumulative total to println at the end?
An ex is as follows:
(Sorry if it isn't formatted correctly, I am working on learning how it should look)
int addons = 0;
do{
addons = JOptionPane.showConfirmDialog(null, "Would the customer like to add Salad, Smoothie, Sundae or Cone?");
if (addons == JOptionPane.NO_OPTION);
else if (addons == JOptionPane.YES_OPTION){
String[] choices2 = { "Salad $"+salad, "Smoothie$"+smoothie, "Sundae $"+sundae, "Cone $"+cone};
String extras = (String) JOptionPane.showInputDialog(null, "Which addon?",
"Extras", JOptionPane.QUESTION_MESSAGE, null, // Use
choices2, // Array of choices
choices2[0]); // Initial choice
count++;//Add item to count
System.out.println(extras);
} //close YES_OPTION parameters
} //close do parameters
while(addons == JOptionPane.YES_OPTION); // Exit do while loop6
I am new to Android application development and am trying to find a way to proceed through a series of screens that take in user input. I'm making a small math game where the user would answer basic two integer addition problems. So far the main menu is created. It has a New Game button which launches my GameActivity and it runs just fine for one math problem. However, after the user inputs their answer to the simple math problem, I would like to be able to continue on to another math problem once the user had answered the current problem and the method would return a correct/incorrect value. Initially I thought of doing something like a basic FOR loop from within the GameActivity :
for(int i = 0; i < 10; i++){ gameMethod(); }
gameMethod() is a JAVA method that simply generates 2 random numbers, adds them to get the correct answer and then prompts the user using an EditText field to type in their guess. It displays the random numbers and answer using TextView boxes created in an XML layout file.
Each call to the gameMethod would, at least I think, just re-input the randomized numbers into the TextView fields displayed on the screen each iteration. I really don't care what the previous numbers were so I figured I would just overwrite them. I wan't able to get the code to do that though. I put in a Log.d() statement or two and found that the FOR loop was in fact running through correctly 10 times, but it was not waiting for user input before firing off its next gameMethod().
In doing some looking around, I found the startActivityForResult() and wondered if this was a more appropriate way of approaching this. So in this way, I foresee having three Activities, the Main menu which calls the GameActivity which would then iterate through, say 10 times, each iteration calling yet another activity GameScreenActivity which would actually put the numbers on the screen, read in user input and then return 1 for a correct answer and 0 for an incorrect answer. So far in reading up on StarActivityForResult() I'm getting somewhat confused by the process and wondered if this was even a plausible path to be exploring.
Again, I'm very new at this Android programming and appreciate any and all help that I can get.
Thank you.
Sorry for not including the gameMethod() initially, I've added it below.
// Create and initialize arrays of integers
int[] a = {0,1,2,3,4,5,6,7,8,9,10};
int[] b = {0,1,2,3,4,5,6,7,8,9,10};
// Creates random number generator
Random randy = new Random();
// Generates two random values to add
int r1 = randy.nextInt(10);
int r2 = randy.nextInt(10);
// Calculates correct answer
int an = a[r1] + a[r2];
// Displays 1st number
TextView number1 = (TextView) findViewById(R.id.firstNumber);
number1.setText(Integer.toString(a[r1]));
// Displays 2nd number
TextView number2 = (TextView) findViewById(R.id.secondNumber);
number2.setText(Integer.toString(b[r2]));
// Displays correct answer
TextView answer1 = (TextView) findViewById(R.id.answerNumber);
//hide answer until user puts in theirs
answer1.setVisibility(View.INVISIBLE);
answer1.setText(Integer.toString(an));
//hide the answer place holder value
TextView uAnswerDisplay = (TextView) findViewById(R.id.userAnswerNumber);
uAnswerDisplay.setVisibility(View.INVISIBLE);
//Get the EditText field that the user will input their answer to
EditText inputText = (EditText) findViewById(R.id.userInput);
//set up a listener to run once the ENTER key is hit after their answer has been entered
inputText.setOnKeyListener(new EditText.OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event){
//only go on the ENTER key when pressed DOWN
if((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)){
EditText innerInputText = (EditText) findViewById(R.id.userInput); //get the EditText box reference
TextView innerUAnswerDisplay = (TextView) findViewById(R.id.userAnswerNumber); //get the TextView box that the answer will go in
String inputString = innerInputText.getText().toString(); //capture the user's input
int uAnswer = Integer.parseInt(inputString); //parse user answer to an integer
int cAnswer = Integer.parseInt((((TextView) findViewById(R.id.answerNumber)).getText()).toString());
innerUAnswerDisplay.setText(Integer.toString(uAnswer)); //display the string after converting from integer
//change colors of text based on correctness
if (uAnswer == cAnswer){ innerUAnswerDisplay.setTextColor(Color.GREEN); } //green for correct
else { innerUAnswerDisplay.setTextColor(Color.RED); } //red for incorrect
innerUAnswerDisplay.setVisibility(View.VISIBLE); //make the user input answer visible
TextView innerAnswer1 = (TextView) findViewById(R.id.answerNumber);
innerAnswer1.setVisibility(View.VISIBLE); //hide answer until user puts in theirs
} //end of if
return false; //return false
} //end of onKey
}); //end of setOnKeyListener
Sorry for all the edits, I couldn't get the edits to include the code and post correctly so I broke it up into chunks and added a little at a time.
From what you say, I'd consider two ways of letting the user answer questions:
have an onclick listener on the input EditText that triggers a new loop;
have a dialog activity that gets started in the beginning of the loop, which prompts the user for a new answer, your game activity would receive the answer via its onActivityResult.