简体   繁体   English

无法在while循环内设置变量

[英]Can't set a variable inside a while loop

New to Java, sorry if this is a stupid question. Java的新手,很抱歉,如果这是一个愚蠢的问题。 I'd like to assign new values to a couple of variables from inside a while loop, but that's not working. 我想从一个while循环中为几个变量分配新值,但这不起作用。 I'm getting an error "The local variable newString may not have been initialized" when trying to compile. 尝试编译时出现错误“本地变量newString可能尚未初始化”。 Here's an example: 这是一个例子:

public class Test {

    public static String example() {
        String first;
        String second;
        String newString;
        int start = 1;

        while (start<5) {
            if (start<4) {
                first = "hello";
                second = "world";
                newString = first + second;
            }
            start += 1;
        }
        return newString;
    }

    public static void main(String[] args) {
            System.out.println(example());
    }
}

You are getting this error because the compiler does not know if newString will ever be initialized before it gets returned. 之所以出现此错误,是因为编译器在返回newString之前不知道newString是否会初始化。

Although you know that both start<5 and start<4 are true and will, thus, execute, the compiler doesn't perform these types of calculations during compilation. 尽管知道start<5start<4都是true并且可以执行,但是编译器在编译期间不会执行这些类型的计算。 Hence, for all it knows, those statements will never execute, and thus newString may get returned before it is initialized. 因此,就其所知,这些语句将永远不会执行,因此newString可能会在初始化之前得到返回。

Hence, you should initialize it (eg to null ) when you declare it to avoid this error. 因此,在声明它时应该初始化它(例如,将其初始化为null ),以避免发生此错误。

There is a rule in Java that all local variables must be initialized before they are first read. Java中有一个规则,即必须先初始化所有局部变量,然后才能对其进行初始化。 You are using newString as a return value, which is a read operation. 您正在使用newString作为返回值,这是一个读取操作。
Although you are assigning a value to newString , it is done in conditional situation ( start<5 && start<4 ). 尽管您正在为newString分配一个值,但它是在条件情况下( start<5 && start<4 )完成的。 At the compile time, the compiler does not know what will be the result of running the code and it conservatively complains about this situation. 在编译时,编译器不知道运行代码的结果,因此保守地抱怨这种情况。

The simple solution will be initializing the string: 简单的解决方案是初始化字符串:

 String newString = "";

When you are returning a variable as a result from a method, the compiler needs to be sure that a value would be assigned to that variable (in your case newString ). 当您从方法返回结果变量时,编译器需要确保将值分配给该变量(在您的情况下为newString )。

Although it is pretty clear for you that the condition start < 4 will be true at some points, the compiler is not intelligent enough to figure that out, which means you have to return only variables, which has values for sure. 尽管您很清楚条件start < 4在某些时候是true ,但是编译器不够智能,无法弄清楚这一点,这意味着您只需要返回肯定具有值的变量。

Depending on the purpose of your method, you have the following opportunities: 根据您的方法的目的,您有以下机会:

String newString = "";

In this case you are sure that your method will never return null , which could be tricky in some cases for finding errors. 在这种情况下,您可以确保您的方法永远不会返回null ,这在某些情况下可能难以发现错误。

Another opportunity is 另一个机会是

String newString = null;

if you want to allow your method to return null values. 如果要允许您的方法返回null值。

As it is obvious in this case that you will eventually enter the if -block and assign a value to the variable newString in other cases it won't be that obvious, so you need to determine whether to allow your method return null values or not. 很明显,在这种情况下,您最终将输入if -block并在其他情况下为变量newString赋值,这种情况并不那么明显,因此需要确定是否允许您的方法返回null值。 。

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

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