Just a brief description of what I am doing - I have random equation generator and buttons with all the digits. In order to answer the question the user has to click the corresponding buttons to form the question(digits are written from left to right) e.g. 9 + 6 = user clicks 1 and 5. If the answer is correct another equation should come up. The issue I am encountering for now is that SOMETIMES when the answer is a single digit there is no new equation showing up, nor any errors or something. Just nothing happens. Most of the time this occurs is when the answer is "0". Any idea what might be causing this ? Here is part of the code :
public void checkAnswer(){
int answer = question.getAnswer();
if(ansID2==-1){
if(String.valueOf(answer).equals(String.valueOf(ansID1))){
makeEquation();
}
}else{
if(String.valueOf(answer).equals(String.valueOf(ansID1) + String.valueOf(ansID2))){
makeEquation();
}
}
}
ansID2 is set to be -1 so if the answer is only a single digit the second digit place is skipped. ansID's are assigned when the button with the digit is clicked.
checkAnswer is called from a button "Check Answer" with the following code
EventHandler checkHandler = new EventHandler(){
#Override
public void handle(Event arg0) {
checkAnswer();
}
};
ansID2 is set to -1 in the field declaration
I would do this numerically:
public void checkAnswer(){
int answer = question.getAnswer();
int response = ansID1;
if(ansID2 >= 0) {
response = 10 * response + ansID2;
} // else a one-digit response
if (answer == response) {
makeEquation();
}
}
At minimum, that's more efficient than performing all the string manipulation you do in the original code. With that said, I don't see why this version would produce different results from yours. I'm inclined to suppose that your real problem is elsewhere, such as either the answer or the response digits being incorrect.
In particular, you say
ansID2 is set to -1 in the field declaration
but that's sufficient only until the first question with a two-digit answer, which will cause ansID2 to be set to something else. It (and also ans1ID) should be reset when a new equation is created.
Related
I am currently working on a game where players are supposed to solve for X + Y with selection of 3 buttons (1 of which is answer) and a "Next" button to go to the next question (by replacing values of components into the next question's). However, I am not able to tally the answers because my tested selection (Button) is always testing the values of the next question
To give a little context,
questionCategories is an ArrayList of ArrayList with different levels
e.g. questionCategories.get(selectedLevel) returns ArrayList of different arithmetics
jumbleOptions populates 3 buttons with correct and incorrect answers which are housed in options
I'm having a situation where when answering Question 1, the shown option values belongs to Question 1, but the tested values (in test) are from Question 2.
e.g.
Qn1: 3 + 5 - A: 2, B: 8, C: 4
Qn2: 8 + 2 - A: 10, B: 11, C:12
When I attempt Qn1 on B and click "Next" to go to the next question (and test for correctness), Instead of testing B:8 my program ends up testing B: 11 instead. I have tried to Log the captured values of each Button and Question's answer but they are all correct and I am not sure where did I go wrong.
The code snippet is within onViewCreated, the first question is initialized to display because of placeholder text in the original element. I'm sorry if the code snippet does not make much sense, trying to keep it short so it's (hopefully) more readable.
// Initialize first question to display
questionNumber.setText("Question " + String.valueOf(qnNumDisplay));
questionTitle.setText(((questionCategories.get(selectedLevel)).get(0)).toString());
jumbleOptions(((questionCategories.get(selectedLevel)).get(0)));
do {
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Question q = (questionCategories.get(selectedLevel)).get(numQnAnswered);
// Increment question number related variable
numQnAnswered++;
// Replace displayable elements with next question
//Question Number
questionNumber.setText("Question " + String.valueOf(numQnAnswered));
questionTitle.setText(q.toString());
jumbleOptions(((questionCategories.get(selectedLevel)).get(numQnAnswered)));
boolean test = checkAnswer(String.valueOf(q.getAnswer()),
options.get(SELECTED_OPTION).getText().toString());
Log.d("Answer Correctness", String.valueOf(test));
}
});
counter++;
} while (counter < NUMBER_OF_QNS);
Let's simulate the scenario:
First question is set up manually, and next question is loaded based on button click. I assume numQnAnswered is 0 and you're getting the answer from your Question object of numQnAnswered th position, right?
final Question q = (questionCategories.get(selectedLevel)).get(numQnAnswered);
As your codes say so.
Notice here, carefully:
// Increment question number related variable
numQnAnswered++;
Now the problem however is, the answer is validated inside button click, I think you've forgot the fact that the first question was set up manually... & before checking the answer for that one you've incremented the numQnAnswered variable, thus your question is one step behind your answer. Hope it make sense.
Just decrement the numQnAnswered variable after the validation of current question.
// Initialize first question to display
questionNumber.setText("Question " + String.valueOf(qnNumDisplay));
questionTitle.setText(((questionCategories.get(selectedLevel)).get(0)).toString());
jumbleOptions(((questionCategories.get(selectedLevel)).get(0)));
do {
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Question q = (questionCategories.get(selectedLevel)).get(numQnAnswered);
// first we need to check answer of previous question
boolean test = checkAnswer(String.valueOf(q.getAnswer()),
options.get(SELECTED_OPTION).getText().toString());
Log.d("Answer Correctness", String.valueOf(test));
// Increment question number related variable
numQnAnswered++;
// Replace displayable elements with next question
//Question Number
questionNumber.setText("Question " + String.valueOf(numQnAnswered));
questionTitle.setText(q.toString());
jumbleOptions(((questionCategories.get(selectedLevel)).get(numQnAnswered)));
}
});
counter++;
} while (counter < NUMBER_OF_QNS);
I have recently started a course where the main language we are learning at the moment is Java.
I have been tasked with creating a program that allows people to vote on two candidates - the program then counts the votes, and depending on how man votes have been made depends on what is displayed.
Here is the part I am concerned with at the moment:
public String printResults(){
if(candidate1Votes == 0 && candidate2Votes == 0)
{
System.out.println ("No votes cast, results cannot be displayed.");
return "No votes cast, results cannot be displayed.";
}
else if(this.completed == false)
{
System.out.println ("Voting has not finished");
return "Voting has not finished";
}
else if(this.completed == true)
{
System.out.println ("Voting has finished, no more votes will be allowed.");
return "Voting has finished, no more votes will be allowed";
}
{
double totalVotes = this.candidate1Votes + this.candidate2Votes;
double cand1Share = (double) this.candidate1Votes/totalVotes*100;
double cand2Share = (double) this.candidate2Votes/totalVotes*100;
System.out.format(candidate1 + " received %3.1f percent of the votes\n", cand1Share);
System.out.format(candidate2 + " received %3.1f percent of the votes\n", cand2Share);
return "v";
}
}
Originally I used void in this method, but part of our task was to then change it to a string value. This is where I am struggling - once I set completed to true, it is still allowing me to cast votes. I know that this code is incomplete but I can't finish it as I am unsure what to do! These were the next parts to the questions.
Modify your printResults method so that it applies the first two rules. Note that the value of the completed field indicates whether or not voting is complete. The method should be modified to return a String which indicates whether printing has been successful.
Modify your vote method to apply the third rule.
Test your methods by creating an instance and doing the following – before
doing each test note the result you expect to get, and compare this with what you actually get:
• Try to print results immediately
• Cast votes for both candidates and try to print results
• Set the completed field to true by calling setCompleted
• Try to cast a vote for a candidate
• Print the results
I am new to this (this is my first year) and have managed to do okay in my books to get this far, however any help on this next issue would be greatly appreciated!
First of your code is unnecessary complicated, which makes it hard to read/enhance. It can easily simplified, like
public String printResults(){
if(candidate1Votes == 0 && candidate2Votes == 0) {
System.out.println ("No votes cast, results cannot be displayed.");
return "No votes cast, results cannot be displayed.";
} // you returned ... NO need for ELSE!
if(this.completed == false) {
System.out.println ("Voting has not finished");
return "Voting has not finished";
}
// it is very clear here that completed must be true!
double totalVotes = this.candidate1Votes + this.candidate2Votes;
double cand1Share = (double) this.candidate1Votes/totalVotes*100;
double cand2Share = (double) this.candidate2Votes/totalVotes*100;
System.out.format(candidate1 + " received %3.1f percent of the votes\n", cand1Share);
System.out.format(candidate2 + " received %3.1f percent of the votes\n", cand2Share);
return "v";
}
Probably that easier-to-read code is all that you need to get you going!
Looking at the code the last block will never be reached because either you have no votes or you have votes and in that case completed will be either true or false and will thus reach always one of the else ifs and they all return a string. So I wonder why how you can cast any votes at all.
You could also post the code where you call printResults and setCompleted to see where the problem lies.
Some more hints for improving your code:
Sometimes you have the opening bracket on the same line and sometimes on the next. You should probably choose one style
It is not necessary to surround the last code block with brackets
if (this.completed == true) and else if (this.completed == false) is a bit redundant and can be written like: if (this.completed) and if (!this.completed). Also you can write
if (this.completed) {
...
} else {
....
}
because if completed is not true it can only be false.
Instead of writing every String two times and having to edit it two times in case you want to change something you could also do the following:
String msg = "Voting has not finished"
System.out.println(msg);
return msg;
I an coding beginner.I have started practicing SPOJ basic problems.This was the one I was trying to solve , But the code is incorrect.
Please help me where I have coded this question wrong as I am unable to figure out:
public class Print2ndChar {
public static void main(String[] args) throws java.lang.Exception {
Print2ndChar mainObj = new Print2ndChar();
java.io.BufferedReader inputReader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
String noOfTestCase;
if(((noOfTestCase = inputReader.readLine()) == null))
System.exit(0);
int noOfLines = 0;
try{
noOfLines = Integer.parseInt(noOfTestCase);
}catch(Exception e){
System.exit(0);
}
if(noOfLines<0 || noOfLines>100)
System.exit(0);
String [] randomWords = new String[noOfLines];
for(int i=0;i<noOfLines;i++){
randomWords[i] = inputReader.readLine();
if(randomWords[i] == null || randomWords[i].length()<2 || randomWords[i].length()%2!=0 || (randomWords[i].length()/2)>100)
System.exit(0);
}
for (String word : randomWords){
mainObj.letsBegin(word.substring(0, word.length() / 2));
System.out.println();
}
}
private void letsBegin(String data) {
if (data.length() <= 0) {
return;
} else {
System.out.print(data.charAt(0));
if (data.length() >= 3)
letsBegin(data.substring(2, data.length()));
}
}
}
EDIT :
I/P : 4
your
progress
is
noticeable
O/P
y
po
i
ntc
OK! So after a lot of hit and trials, I know what is wrong with your code. The code that you have written fails because of the condition randomWords[i].length()%2!=0 inside your if. There is nothing wrong with you putting this condition to check the input, but if you will select sample test case, inside the highlighted blue area you will notice an extra space after every string. Like this :
You can see that other than the last input all other input strings have a space character at the end. So, when you read the string from stdin the length of the string is 2*k + 1 (because of the space), and your program will exit without any output. Hence you get a wrong answer.
This problem exists with other test cases as well probably. And how do I know this? After spoj shows you wrong answer, if you click on the wrong answer, it will show you 2 failed test cases, something like this:
It shows your program's output is empty because your code exited because of the extra space at the end of strings.
So, I believe the person who wrote the test cases should be given a WT Error (Wrong Test Cases) :P :D
So, the possible correction is you remove the mentioned condition from the if and you will get AC. Because now you will be dividing 2*k + 1 by 2, which will not be an integer and which will get rounded to the nearest smallest integer, which will be same as dividing 2*k by 2 and the program will give the correct result.
A few things that you should take care while solving questions on spoj, you do not have to verify that every input lies within the range specified in the question, or if it is a valid data type. The range is given to tell you that Spoj will only test your program with cases which lie between those ranges and will not exceed them. So, even if you remove all the code where you check for exceptions and ranges of input data, you will get an AC. Moreover, writing such code only adds to the burden.
Hope this helps. :)
I have ten buttons, 0-9 and when one is pressed I want to display its value into a TextView. So the initial display looks like this:
0.00
If I press the 2 button then it should be displayed to the TextView like this:
0.02
Now if I pressed 5 then the new value should be:
0.25
and so on. I've never done anything like this so I'm not exactly sure where to begin. So my question is, whats the best way to implement something like this?
EDIT: I know how to display content when a button is pressed, however, I'm not sure how to transition the each number when a new button is pressed into its new position.
Store an int with the value you are displaying and as you input the number multiply that value by 10 and add the new number on.
Something like:
public void updateValue(int buttonPressed){
currentValue = (currentValue*10) + buttonPressed;
}
then where you're updating the TextView make sure you format the string in a suitable way:
public String formatNum(){
String valueAsString = Integer.toString(currentValue);
while(valueAsString.length()<3){
valueAsString = '0' + valueAsString;
}
char[] stringBuilding = new char[valueAsString.length()+(((valueAsString.length())-2)/3)+1];
int valueAsStringPtr = valueAsString.length()-1;
int stringBuildingPtr = stringBuilding.length-1;
while(stringBuildingPtr>=0){
if(stringBuildingPtr==stringBuilding.length-3){
stringBuilding[stringBuildingPtr--] = '.';
} else if((stringBuilding.length-stringBuildingPtr-3)%4==0){
stringBuilding[stringBuildingPtr--] = ',';
} else {
stringBuilding[stringBuildingPtr--] = valueAsString.charAt(valueAsStringPtr--);
}
}
String returnVal = String.copyValueOf(stringBuilding);
return returnVal;
}
All this assumes you have an integer field currentValue.
Also try to do this on a worker thread ideally to avoid lagging out UI, it shouldn't really take too long, but still a good idea.
Note: for anyone wondering why I elected to use ints instead of float/double is because then we will introduce error displaying a binary representation as a decimal.
Hi I am making an android App, I want to add some values to a database and I want to do N times so I used a for loop as seen below:
private void addCodeToDataBase() {
for (int i = 1; i <= 100; i++) {
//indexnumber is a TextView
indexNumber.setText("Please enter the TAN code for Index number " + i);
//tanCode is an EditText
if (tanCode.getText().toString() != null) {
//index here is just an int so i can use the i inside the onClick
index = i;
//add is a button
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String codeText = tanCode.getText().toString();
dbHandler.addcode(index, codeText);
}
});
} else {
Toast.makeText(addcode.this, "Please enter your code !!!", Toast.LENGTH_LONG).show();
}
}
}
but what I am facing here is the for loop jumps to 100 at the first run, What I mean is the text will show :
Please enter the TAN code for Index number 100
it skips 99 numbers!! how would I fix it ?
It's Because your for loop executes so fast that you can't notice that the change of the text.First i is 0,and then it becomes 1,then the text will be "Please enter the TAN code for Index number 1" ......
your loop is working correctly but it is replacing text on each iteration that's why you think that it is jumping on last value please use break point and debug you will see each value on each iteration or use log in which you will see each value
It's not easy to imagine what your code does without seeing your declarations of indexNumber, tanCode, index, and, in particular, add. So, e.g., we don't know how often your if condition yields true.
However, most probably, the problem is that your assignment add.setOnClickListener(...) is just iterated with no user interaction in between. Now if you repeatedly assign something to your add (whatever that is), the last assignment will win.
If you want 100 buttons, you'll need to have an array or List of buttons to press, where each has a different tan code. If you want one button that repeatedly asks for the different tans, then you have to assign the data for click i + 1 only after click i has been handled, i.e. in the on click listener.
To give more specific help, we would need to know how your user interface should look (how many widgets of what kind) and how each widget should behave.