0

私はプログラミングが初めてです。これの何が問題なのかを見つけるのに苦労しています。メッセージに表示されるテキストをランダム化しようとしているアラート ビューです。

-(void)alert:(id)sender{
int randomNumber;
randomNumber = (randomNumber() %3 + 1);
NSLog(@"%i", randomNumber);

if (randomNumber == 1) {
    self.YouWin.text = [NSString stringWithFormat:@"You Win"];
}
else if (randomNumber == 2) {
    self.YouWin.text = [NSString stringWithFormat:@"You Lose"];
}
else if (randomNumber == 3) {
    self.YouWin.text = [NSString stringWithFormat:@"Tie"];
}
NSLog(@"%@",YouWin);
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Hello" message:[NSString stringWithFormat:@"%@",YouWin] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alert show];
button.hidden = YES;
4

4 に答える 4

0

交換

randomNumber = (randomNumber() %3 + 1);

randomNumber = arc4random() %3 + 1;

これも使って...

if (randomNumber == 1) {
self.YouWin.text = [NSString stringWithFormat:@"You Win"];
}
else if (randomNumber == 2) {
self.YouWin.text = [NSString stringWithFormat:@"You Lose"];
}
else if (randomNumber == 3) {
self.YouWin.text = [NSString stringWithFormat:@"Tie"];
}
NSLog(@"%@",YouWin);


UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Hello" 
                                               message:self.YouWin.text 
                                              delegate:self 
                                     cancelButtonTitle:@"Ok" 
                                     otherButtonTitles:nil];

[alert show];
button.hidden = YES;
于 2013-04-11T17:20:23.403 に答える
0

Anoopが指摘したように、使用してstringWithFormatいますが、フォーマット文字列をまったく提供していません。

やったほうがいい

[NSString stringWithFormat:@"%@", @"You Win"];

しかし、それは正しいとはいえ、非常に冗長であり、単に を使用するのとまったく同じ@"You Win"です。

また、問題に対する一般的なアプローチについてのアドバイス。大きなif-elseステートメントを作成する代わりに、すべての文字列をデータ構造に格納してからランダムにアクセスする方がよいでしょう。

コードでは、これは次のように変換されます

NSArray * outcomes = @[ @"You Win", @"You lose", @"Tie" ];
int randomIndex = arc4random_uniform(outcomes.count);
NSString * randomOutcome = outcomes[randomIndex];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Hello"
                                               message:randomOutcome
                                              delegate:self
                                     cancelButtonTitle:@"Ok"
                                     otherButtonTitles:nil];
[alert show];
button.hidden = YES;

arc4random_uniform()を使用すると、0 と提供された引数の間の乱数が返されることに注意してください。

于 2013-04-11T17:22:10.127 に答える