随机数发生器(命令行)

时间:2016-11-17 13:34:35

标签: swift command-line

当用户输入数字时,他们必须猜测随机数。这些是我在代码中获得两次代码的错误。

"类型的值"字符串没有数字" stringByReplacingOccruencesOfString"

input = input.stringByReplacingOccurrencesOfString("\n", withSring:"",

这是完整的代码

import Foundation

var randomNumber = 1
var userGuess:Int? = 1
var continueGuessing = true
var keepPlaying = true
var input = ""

while (keepPlaying) {
randomNumber = Int(arc4random_uniform(101)) 
// gets a random number between 0-   1000

print("The random number to guess is:\(randomNumber)");
while (continueGuessing) {
    print ("Print a number between 0 and 100")
    input = NSString(data: FileHandle.standardInput.availableData,
    encoding:String.Encoding.utf8.rawValue) as! String // gets keyboard input
    input = input.stringByReplacingOccurrencesOfString("\n", withSring:"",
    options: NSString.CompareOptions.LiteralSearch, range: nil)
    userGuess = Int(input)
    if (userGuess == randomNumber){
        continueGuessing = false
        print("Correct Number!");
    }
    else if (userGuess! > randomNumber){
        print("Your guess is too high");
    }
    else{
        print("Your guess is too low");

    }
}
print ("Play Again? Y or N");
input = NSString(data: FileHandle.standardInput.availableData,
encoding:String.Encoding.utf8.rawValue)! as String
input = input.stringByReplacingOccurrencesOfString("\n", withString: "",
options: NSString.CompareOptions.LiteralSearch, range: nil)

if(input == "N" || input == "n"){
    keepPlaying = false
}
continueGuessing = true

}

1 个答案:

答案 0 :(得分:0)

固定代码

import Foundation

var randomNumber = 1
var userGuess:Int? = 1
var continueGuessing = true
var keepPlaying = true
var input = ""

while (keepPlaying) {
randomNumber = Int(arc4random_uniform(101))
// gets a random number between 0-   1000

print("The random number to guess is:\(randomNumber)");
while (continueGuessing) {
    print ("Print a number between 0 and 100")
    if let input = readLine() {
        if let userGuess = Int(input) {
            if (userGuess == randomNumber){
                continueGuessing = false
                print("Correct Number!");
            }
            else if (userGuess > randomNumber) {
                print("Your guess is too high");
            }
            else{
                print("Your guess is too low");

            }

        } else {
            print("Bad input data");
        }
    }
}
print ("Play Again? Y or N");
input = readLine()!
if(input == "N" || input == "n"){
    keepPlaying = false
}
continueGuessing = true

}

结果

enter image description here