局部变量是冗余intellij

Ste*_*ef 2 java intellij-idea

public static double getAmount(){
    Scanner reader = new Scanner(System.in);
    System.out.println("random text");
    double amount;
    return (amount = reader.nextDouble());
}
Run Code Online (Sandbox Code Playgroud)

IntelliJ在上面的代码中给出了这个警告:

局部变量'amount'是多余的

为什么?

Ric*_*out 11

在方法体的末尾(在{和}之间)声明的任何变量都将被删除(垃圾收集).(除非您将其设置为未在方法体中创建的内容)

您在运行时创建变量"amount":

 double amount;
Run Code Online (Sandbox Code Playgroud)

此时您已创建变量但从未为其分配值.第一次使用此变量位于return语句中:

return (amount = reader.nextDouble());
Run Code Online (Sandbox Code Playgroud)

你应该做的是在与声明相同的行上分配变量:

public static double getAmount(){
    Scanner reader = new Scanner(System.in);
    System.out.println("random text");
    double amount  = reader.nextDouble();
    return amount;
}
Run Code Online (Sandbox Code Playgroud)

或者,更好的是,根本不要使用变量(尽管它可以提高代码的可读性,在这种情况下可以保留一个有效点):

public static double getAmount(){
        Scanner reader = new Scanner(System.in);
        System.out.println("random text");

        return reader.nextDouble();
    }
Run Code Online (Sandbox Code Playgroud)

为什么Intellij警告我?
Intellij只是告诉你最后你的变量没有被使用(它不是)所以删除变量声明是安全的.

但是,如果你将鼠标悬停在你的代码行开头出现的小灯泡上,Intellij也应该为你提供一个解决方案.一个例子: 在此输入图像描述