我是编程世界的新手,正在尝试使用简单的数学应用程序。基本上我想app创建两个随机数,然后将它们加在一起。然后我将答案放在文本字段中,应用程序检查答案是对还是错。我创建了这个并且它可以工作但是在答案正确后我无法重新生成数字。你可以给我的任何方向我都会非常感激。
这是代码。
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.guess(self)
}
@IBOutlet weak var addend1: UILabel!
@IBOutlet weak var addend2: UILabel!
@IBOutlet weak var answer: UITextField!
@IBOutlet weak var response: UILabel!
//create numbers
let newaddend1 = arc4random() % 11
let newaddend2 = arc4random() % 11
@IBAction func guess(sender: AnyObject) {
//Convert Random Numbers to String to be displayed in labels
var firstNumber = String(newaddend1)
var secondNumber = String(newaddend2)
//convert the answer in the text field to an integer
var integer = answer?.text.toInt()
//Convert Strings to Ints so they can be added
var newFirstNumber = firstNumber.toInt()
var newSecondNumber = secondNumber.toInt()
//Add Numbers
var correctAnswer = (newFirstNumber! + newSecondNumber!)
//Display the numbers
addend1.text = firstNumber
addend2.text = secondNumber
//Print correct number to log for test
println(correctAnswer)
println(integer)
//check your answer agains the correct answer
if (integer != nil) {
if (integer == correctAnswer) {
response.text = "Correct! The Answer is \(correctAnswer)!"
} else {
response.text = "Wrongo Bongo the correct answer is \(correctAnswer)!"
}
} else {
response.text = "Please put in a number for your guess"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//remove keyboard
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true)
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
answer.resignFirstResponder()
return true
}
}
答案 0 :(得分:0)
您可以初始化IBAction之外的变量以获取类级变量声明。然后在生成正确答案后立即计算新的随机数:
let newaddend1 = 0
let newaddend2 = 0
@IBAction func guess(sender: AnyObject) {
//Convert Random Numbers to String to be displayed in labels
var firstNumber = String(newaddend1)
var secondNumber = String(newaddend2)
//convert the answer in the text field to an integer
var integer = answer?.text.toInt()
//Convert Strings to Ints so they can be added
var newFirstNumber = firstNumber.toInt()
var newSecondNumber = secondNumber.toInt()
//Add Numbers
var correctAnswer = (newFirstNumber! + newSecondNumber!)
//Display the numbers
addend1.text = firstNumber
addend2.text = secondNumber
//Print correct number to log for test
println(correctAnswer)
println(integer)
//check your answer agains the correct answer
if (integer != nil) {
if (integer == correctAnswer) {
response.text = "Correct! The Answer is \(correctAnswer)!"
let newaddend1 = arc4random() % 11
let newaddend2 = arc4random() % 11
} else {
response.text = "Wrongo Bongo the correct answer is \(correctAnswer)!"
}
} else {
response.text = "Please put in a number for your guess"
}
}