简体   繁体   English

为什么不能解析这些变量?

[英]Why can't these variables be resolved?

I need to write a program and, in one step of it, I need to construct a function that calculates the number of rabbits.我需要编写一个程序,在其中的一个步骤中,我需要构建一个计算兔子数量的函数。

The problem is that Eclipse shows a message saying that the variable I created "cannot be resolved to a variable" and I don't understand why it happens.问题是 Eclipse 显示一条消息,说我创建的变量“无法解析为变量” ,我不明白为什么会发生这种情况。 Can someone help me?有人能帮我吗?

Here is part of my code这是我的代码的一部分

I am showing all my code because it would get bigger and it is not needed, in order to solve this problem我展示了我所有的代码,因为它会变大并且不需要它,以解决这个问题

class Rabbits {
    static int nbRabbits = initRabbits;        // ERROR HERE!!!!!!!!!!!!!!!!!!!!!!!!!!
    static int nbFoxes = initFoxes;           // ERROR HERE!!!!!!!!!!!!!!!!!!!!!!!!!!
    int rabbits = 0;

    public static int calculateRabbits(int rabbits, int foxes, double AttackRate) {
        for (int i = 0; i < Duration; ++i) {
            rabbits = nbRabbits;
            nbRabbits *= (1.0 + Rabbits_growth_rate - AttackRate * nbFoxes);
        }
        return nbRabbits;
    }

    public static void main(String[] args) {
        Scanner keyb = new Scanner(System.in);

        // Enter initial population
        int initFoxes = enterPopulation("foxes", 2, keyb); //at least 2 foxes
        int initRabbits = enterPopulation("rabbits", 5, keyb); //at least 5 rabbits

        // SOME MORE CODE HERE
    }   // end main
} // end of class

initRabbits and initFoxes are variables entered by the user when I call enterPopulation method. initRabbitsinitFoxes是用户在调用enterPopulation方法时输入的变量。

I'm new to Java and, unfortunately, I cannot change the logic of this code.我是 Java 新手,不幸的是,我无法更改此代码的逻辑。 For example, I cannot put the calculateRabbits method inside the main neither change the begin or the end of the code.例如,我不能将calculateRabbits方法放在main也不能更改代码的开头或结尾。

initRabbits only exists within the main method. initRabbits只存在于 main 方法中。 That is it's scope .那就是它的范围

You are attempting to statically reference something it can't see.您正试图静态引用它看不到的东西。 You are attempting to populate nRabbits before a value for innitRabbits exists.您正在尝试在 innitRabbits 的值存在之前填充 nRabbits。 This is impossible.这是不可能的。

Your trying to assign a value to your nb variables from a variable that hasn't been created yet.您试图从尚未创建的变量中为 nb 变量赋值。 Skip making four variables and just assign the nbs to 0 outside of your main class, then give them the value you want inside it.跳过创建四个变量,只需在主类之外将 nbs 赋值为 0,然后在其中为它们提供所需的值。 They will then retain that value outside of the main class and be visible.然后,它们将在主类之外保留该值并可见。

static int nbRabbits = 0;
static int nbFoxes = 0;

//in main class
nbFoxes = enterPopulation("foxes", 2, keyb); //at least 2 foxes
nbRabbits = enterPopulation("rabbits", 5, keyb); //at least 5 rabbits 

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

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