1

I have checked my code thrice and not able to find any error in it but my output is showing me the wrong answer. The code is of the simple adding game tester.

import UIKit

class ViewController: UIViewController {

    var score = 0
    var firstNumber: Int?
    var secondNumber: Int?
    var answer: Int?
    var input: Int?
    var count = 0
    @IBOutlet weak var lblTitleLabelOUTLET: UILabel!
    @IBOutlet weak var lblEquationOUTLET: UILabel!
    @IBOutlet weak var txtAnswerFieldOUTLET: UITextField!
    @IBOutlet weak var btnCheckAnswerOUTLET: UIButton!
    @IBOutlet weak var lblScoreDisplayerOUTLET: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
    displayQuestion()


}

    @IBAction func pressedCheckedAnswerButtonACTION(sender: UIButton) {
        if (input == answer){
            score = score + 1
            lblScoreDisplayerOUTLET.text = "Your score is \(score) out of \(count) "
            }
        else{
            lblScoreDisplayerOUTLET.text = "Incorrect ans "
        }
    displayQuestion()
    }

    func displayQuestion() {

        firstNumber = Int(arc4random_uniform(10))
        secondNumber = Int(arc4random_uniform(10))
        lblEquationOUTLET.text =  String(firstNumber!) +  "  +  "  + String(secondNumber!) +  "  =  "
        answer = firstNumber! + secondNumber!
        input = Int(txtAnswerFieldOUTLET.text!)
        lblTitleLabelOUTLET.text = String(input)

        count = count + 1
        }

}
pacholik
  • 8,607
  • 9
  • 43
  • 55

1 Answers1

2

You are computing input when you create and display the question. You need to move that code to the top of pressedCheckedAnswerButtonACTION.

@IBAction func pressedCheckedAnswerButtonACTION(sender: UIButton) {
    input = Int(txtAnswerFieldOUTLET.text!)

    if input == answer {
        score = score + 1
        lblScoreDisplayerOUTLET.text = "Your score is \(score) out of \(count) "
    }
    else {
        lblScoreDisplayerOUTLET.text = "Incorrect ans "
    }
    displayQuestion()
}
vacawama
  • 150,663
  • 30
  • 266
  • 294
  • It worked out for me. But could you explain me explicitly how it worked. Thanks for helping – Yashwin Munsadwala Oct 09 '16 at 12:46
  • It all has to do with timing. The way you had it coded, the variable `input` was computed when the question was displayed, which is too early. You need to wait until the user has typed in their answer and pressed the button. With my change, `input` is assigned after the user has input their answer and pressed the button. – vacawama Oct 09 '16 at 12:51