简体   繁体   English

为什么在 for 循环中初始化变量时,我会收到“变量可能没有为变量 a、b 和 n 初始化”?

[英]Why am I getting "variable might not have initialized for variables a,b and n" while they are initialized in a for-loop?

I tried to take input by stdin and I want "t" times the value of a , b and n .我试图通过stdin获取输入,我想要"t"乘以abn的值。 But I am getting compile error the variable might not have been initialized for the variables a , b and n .但我收到编译错误变量可能尚未为变量abn初始化

I am not able to figure out where I went wrong.我无法弄清楚我哪里出错了。

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*; 

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        int num;
        Scanner in = new Scanner(System.in);
        num = in.nextInt();             
        int sol;             
        sol=  takken(num);
        System.out.println(sol);
    }

    public static int takken(int howManyTimes){
        int a, b, n;
        int x;
        int solution = 0;
        Scanner d = new Scanner(System.in);
        int y = 4;
        for(int j = 0; j< y; j++)
        {
            a = d.nextInt();
            b = d.nextInt();
            n = d.nextInt();
        }
        solution = a;
        int temp = 0;

        for ( int i = 0; i < n; i++ ){
            x = (int) Math.pow(2,i);
            temp =  x * b;

            solution = solution + temp;
        }
        return solution;
    }
}

Just change your declaration of a , b and n to:只需将abn声明更改为:

int a = 0, b = 0, n = 0;

The Java compiler cannot tell that you have initialized these variables in the for-loop because you are going through the for-loop a variable number of times (that number being the variable y ). Java 编译器无法判断您已经在 for 循环中初始化了这些变量,因为您正在执行 for 循环可变次数(该次数是变量y )。

Although you declared y to have the value 4 just above the for-loop, and we can see that this means that your variables will always get a value, this is not seen by the Java compiler.尽管您在 for 循环的正上方声明了y的值为4 ,并且我们可以看到这意味着您的变量将始终获得一个值,但 Java 编译器看不到这一点。

The Java compiler follows a number of strict rules when checking whether something is certain to have been initialized; Java 编译器在检查某些东西是否已被初始化时遵循许多严格的规则; and if you initialize them in a loop that is iterated over a variable number of times, even if the variable is set before, Java still doesn't see that.并且如果您在一个循环中初始化它们,该循环迭代可变次数,即使变量之前已设置,Java 仍然看不到这一点。

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

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