简体   繁体   English

返回if语句

[英]Return in if statement

I've been coding a text adventure game in C#. 我一直在用C#编写文本冒险游戏。 I want to do a scene where you encounter a pokemon. 我想做一个遇到宠物小精灵的场景。 I want to have 3 random pokemon to encounter, and I made a method that returns the name of the pokemon you find. 我想遇到3个随机的宠物小精灵,并且我做了一个方法,可以返回找到的宠物小精灵的名字。 Code is: 代码是:

public string choosePokemon()  
{  
    Random random = new Random();  
    int pokemonChosen = random.Next();  
    if (pokemonChosen == 1)  
    {  
        string pokemon = "Pidgey";  
        return pokemon;  
    }  
    if (pokemonChosen == 2)   
    {  
        string pokemon = "Charmander";  
        return pokemon;  
    }  
    if (pokemonChosen == 3)  
    {  
        string pokemon = "Geodude";  
        return pokemon;  
    }  
    return "missingno";  
} 

Whenever I execute the code it says "You encountered a missingno!". 每当我执行代码时,它都会说“您遇到了失落的人!”。 I want it to return the name and break the method, returning to the method of the scene. 我希望它返回名称并中断方法,返回场景的方法。 I put a return "missingno"; 我把return "missingno";作为return "missingno"; at the end because Studio would give me an error that not all code paths return a value. 最后,因为Studio会给我一个错误,即并非所有代码路径都返回一个值。

Random.Next() (with no parameters) will return a random non-negative integer. Random.Next() (不带参数)将返回一个随机的非负整数。 You probably meant to constrain it to a certain range, like this: 您可能打算将其限制在一定范围内,如下所示:

int pokemonChosen = random.Next(1, 4);

Also note, you can make your code a bit cleaner by just returning a constant inside your if -block like this: 还要注意,您可以通过仅在if -block内部返回一个常量来使代码更加简洁:

if (pokemonChosen == 1)  
{  
    return "Pidgey";  
}  

Or even better, encapsulate your random options in an array. 甚至更好的是,将随机选项封装在数组中。 That way you can get rid of all your if -blocks entirely: 这样,您可以完全摆脱所有if -blocks:

var options = new [] { "Pidgey", "Charmander", "Geodude" };
int pokemonChosen = random.Next(options.Length); // array indexes start at 0
return options[pokemonChosen];

The problem is that your random.Next() call is returning a number anywhere in the range of random - You need an alternate version of random.Next() that returns only 1, 2, or 3, or you need to perform that yourself. 问题是您的random.Next()调用将在random范围内的任何地方返回数字-您需要random.Next()的替代版本,该版本仅返回1、2或3,或者您需要自己执行。 Try doing this instead: int pokemonChosen = random.Next(1, 4) (The lower bound is inclusive while the upper bound is exclusive) 改为尝试执行以下操作: int pokemonChosen = random.Next(1, 4) (下限为包含性,上限为排除性)

A good way to do this, as I've found through trials with my own Pokemon based game, is to put the New Random() outside the function. 正如我在基于自己的Pokemon游戏的试验中发现的那样,执行此操作的一种好方法是将New Random()放在函数之外。 Also, you could instantiate the string outside the function, as well, in case you have different Pokemon options for different parts of the game. 另外,如果您在游戏的不同部分使用不同的Pokemon选项,也可以在函数外部实例化字符串。 This way, you wouldn't have to return anything, just call the function then use the string. 这样,您无需返回任何内容,只需调用函数然后使用字符串即可。 Assuming you're doing a windows based with a label for story output: 假设您正在基于带有故事输出标签的窗口进行操作:

Random random = new Random();
string pokemon;

    public void choosePokemon()  
    {   
        int pokemonChosen = random.Next(2);  
        if (pokemonChosen == 0) {
        pokemon = "Pidgey";
        }
        if (pokemonChosen == 1) {
        pokemon = "Charmander";
        }
        if (pokemonChosen == 2) {
        pokemon = "Geodude";
        }
    } 

    lblStory.Text += "You encountered a wild " + pokemon + "!";

I did something very similar for a game I made for a friend. 我为朋友制作的游戏做了类似的事情。

EDIT: Also, something else I did in my game was to shorten pokemon in variable names to pkmn. 编辑:另外,我在游戏中做的其他事情是将变量名称中的神奇宝贝缩短为pkmn。 Shorter to type, and as seen through the main games, commonly accepted. 从主要游戏中可以看出,字体较短,通常被接受。 Not that the players will read your code. 并不是说玩家会读你的代码。

Lets start with the Random number generator. 让我们从Random数生成器开始。 To be effective, you should only instantiate Random once. 为了有效,您只应实例化Random一次。 To do this, you might make a static instance of it for the class. 为此,您可以为该类创建一个静态实例。 If you don't, it's possible to get the same number back each time you call random.Next() . 如果不这样做,则每次调用random.Next()时都可以取回相同的数字。

public class PokemonChooser
{
    private static Random random = new Random();

    public static string ChoosePokemon() { ... }
}

Then, we need to realize that random.Next() returns any non-negative integer value, not just the ones you want. 然后,我们需要认识到random.Next()返回任何非负integer数值,而不仅仅是您想要的值。 So, we need to round the result to something that's useful for your case. 因此,我们需要将结果四舍五入为对您的案例有用的东西。 Since you have 3 items from which you would like to randomly choose, we can round it using the modulus operator ( % ), which basically gives you the remainder of a division operation ( / ). 由于您有3个要随机选择的项目,因此我们可以使用模运算符( % )对其进行四舍五入,基本上可以得到除法运算的其余部分( / )。 For instance: (int)(5 / 2) == 2 , and 5 % 2 == 1 . 例如: (int)(5 / 2) == 25 % 2 == 1

var pokemonChosen = random.Next() % 3;

Next, since this result is zero-based, we'll need to account for that in the if statements. 接下来,由于此结果是从零开始的,因此我们需要在if语句中加以说明。

      if (pokemonChosen == 0)
      {
        string pokemon = "Pidgey";
        return pokemon;
      }

      if (pokemonChosen == 1)
      {
        string pokemon = "Charmander";
        return pokemon;
      }

      if (pokemonChosen == 2)
      {
        string pokemon = "Geodude";
        return pokemon;
      }

Since the Pokemon names are pretty obvious, we can get rid of the pokemon variable without losing any readability. 由于口袋妖怪的名字很明显,我们可以摆脱pokemon变量而不会失去任何可读性。

      if (pokemonChosen == 0)
      {
        return "Pidgey";
      }

      if (pokemonChosen == 1)
      {
        return "Charmander";
      }

      if (pokemonChosen == 2)
      {
        return "Geodude";
      }

We could probably make this clearer and shorter by using a case statement instead of multiple if statements. 通过使用case语句而不是多个if语句,我们可以使这一点更清楚,更短。

      switch (pokemonChosen) {
        case (0): return "Pidgey";
        case (1): return "Charmander";
        case (2): return "Geodude";
      }

And since we simply return "missingno" if the we cant find the pokemon by number, we can use a default case: 而且由于我们无法通过数字找到口袋妖怪,因此我们只返回"missingno" ,因此我们可以使用默认情况:

      switch (pokemonChosen) {
        case (0): return "Pidgey";
        case (1): return "Charmander";
        case (2): return "Geodude";
        default: return "missingno";
      }

All in all, we end up with: 总而言之,我们最终得到:

public class PokemonChooser
{
    private static Random random = new Random();

    public static string ChoosePokemon()
    {
      var pokemonChosen = random.Next() % 3;

      switch (pokemonChosen) {
        case (0): return "Pidgey";
        case (1): return "Charmander";
        case (2): return "Geodude";
        default: return "missingno";
      }
    }
}

And we use it like so: 我们这样使用它:

var pokemon = PokemonChooser.ChoosePokemon();

However, you may want to choose a higher number than 3 in random.Next() % 3 , otherwise, "missingno" will never be returned. 但是,您可能希望在random.Next() % 3选择大于3random.Next() % 3 ,否则,将永远不会返回"missingno"

You need to specify the upper bound for random.Next() : 您需要指定random.Next()的上限:

int pokemonChosen = random.Next(4);

would return an integer in the range 0 - 3. 将返回范围为0-3的整数。

To have it return 1-4 you could use: 要使其返回1-4,可以使用:

int pokemonChosen = random.Next(1, 5);

You need to specify the range of the random value: 您需要指定随机值的范围:

int pokemonChosen = random.Next(3) + 1;

Otherwise, the range of values is up to Int32.MaxValue, which gives you about a one-in-a-billion chance of being between 1-4. 否则,值的范围最大为Int32.MaxValue,这为您提供介于1-4之间的十亿分之一的机会。

Random.next() will return a value between 0 and 2,147,483,647 (= Integer.MaxValue) so the chance of your number being 1,2 or 3 is slim, that's way it usually returns the last value. Random.next()将返回0到2,147,483,647(= Integer.MaxValue)之间的值,因此您的数字为1,2或3的可能性很小,这通常会返回最后一个值。 You need to limit the value: 您需要限制该值:

random.Next(1, 4);

You shouldn't recreate the Random class every call. 不应该在每次调用时都重新创建 Random类。 And call it like: _random.Next(3) + 1 然后像这样调用它: _random.Next(3) + 1

Random _random = new Random();  

public string choosePokemon()  
{  
     int pokemonChosen = _random.Next(3) + 1;  
     if (pokemonChosen == 1)  
     {  
         string pokemon = "Pidgey";  
         return pokemon;  
     }  
     if (pokemonChosen == 2)   
     {  
         string pokemon = "Charmander";  
         return pokemon;  
     }  
     if (pokemonChosen == 3)  
     {  
         string pokemon = "Geodude";  
         return pokemon;  
    }  
    return "missingno";  
} 

You are gettting a value other than 1, 2, or 3 , debug it and check what the value of pokemonChosen is. 您获取的值不是1, 2, or 3 ,请对其进行调试并检查pokemonChosen的值是什么。 You may wish to limit max value of your random val to be 3 您可能希望将随机值的最大值限制为3

int pokemonChosen = random.Next(4);

tested, your code works correctly - not sure what code you actually used, the exact method that you have always works correctly. 经过测试,您的代码可以正常工作-不确定您实际使用的代码是什么,您始终可以正确使用的确切方法。 however, you should change it to 但是,您应该将其更改为

int pokemonChosen = random.Next(1, 4);  

Upd: hey, way to go changing that line in your original question, when I opened it you had int pokemonChosen = random.Next(1, 3); Upd:嘿,要更改原始问题的方法,当我打开它时,您有int pokemonChosen = random.Next(1,3); in there... 在那里...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM