为什么我在 for 循环中初始化它们时会得到"variable might not have initialized for variables a,b and n"?



我试图通过stdin获取输入,我想要"t"乘以abn的值。但我得到了编译错误,变量abn的变量可能没有初始化。

我不知道哪里出了问题。

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;
    }
}

只需将abn的声明更改为:

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

Java编译器无法判断您已经在for循环中初始化了这些变量,因为您要通过for循环的次数是可变的(该数字是变量y(。

尽管您声明y的值4刚好高于for循环,并且我们可以看到这意味着您的变量将始终获得一个值,但Java编译器看不到这一点。

Java编译器在检查某个东西是否一定已经初始化时遵循许多严格的规则;如果你在一个循环中初始化它们,这个循环迭代了可变的次数,即使这个变量是以前设置的,Java仍然看不到这一点。

最新更新