Java:为什么这段代码不能工作,它说我的变量无法解析

时间:2016-08-22 06:36:44

标签: java

import java.util.Scanner;
public class HowManyToKeep {

    public static void main(String[] args) {
        int currentcandies;
        int currentamountofpokemon;
        int howmanycandiestoevolve;
        int keepamount;
        int x =0;

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter how many candies you have: ");
        currentcandies = sc.nextInt();
        System.out.println("Enter how many pokemon you have: ");
        currentamountofpokemon = sc.nextInt();
        System.out.println("Enter how many candies to evolve: ");
        howmanycandiestoevolve = sc.nextInt();
        sc.close();

        for (int i=0;i<100;i++) {
        int grosstotalcandies = currentcandies + currentamountofpokemon;
        int howmanycanevolve = grosstotalcandies / howmanycandiestoevolve;
        int totalamountofcandies = howmanycanevolve + grosstotalcandies;
        }

        keepamount = totalamountofcandies / howmanycandiestoevolve;
        System.out.println("The total amount you should keep is: " + keepamount);

    }


}

所以我的问题是,为什么当我在循环中定义它时,变量“totalamountofcandies”无法解析?我应该如何让它工作

3 个答案:

答案 0 :(得分:4)

LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); RecyclerView myList = (RecyclerView) findViewById(R.id.my_recycler_view); myList.setLayoutManager(layoutManager); 的范围仅在循环内。要在循环外访问它,必须在循环之前声明它。

除此之外,我假设您要添加循环中收集的所有值,而不是在每次迭代中覆盖totalamountofcandies的值:

totalamountofcandies

答案 1 :(得分:0)

变量在for循环中声明(范围在for循环中)。您正试图在外面进行循环访问。在这个地方,变量不适用于java编译器。所以它抛出一个错误。这应该适合你。

int totalamountofcandies = 0;
for (int i=0;i<100;i++) {
int grosstotalcandies = currentcandies + currentamountofpokemon;
int howmanycanevolve = grosstotalcandies / howmanycandiestoevolve;
totalamountofcandies += howmanycanevolve + grosstotalcandies;
}

现在,您可以访问该程序中任何位置的totalamountofcandies。

答案 2 :(得分:-2)

你必须使变量成为全局变量,该变量的范围在两个大括号内,