简体   繁体   English

局部变量是冗余的 JetBrains IDE(例如 IntelliJ IDEA)

[英]Local variable is redundant JetBrains IDEs (e.g. IntelliJ IDEA)

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

IntelliJ gives me this warning on the above code: IntelliJ 在上面的代码中给了我这个警告:

Local variable 'amount' is redundant局部变量 'amount' 是多余的

Why?为什么?

Any variable declared inside a method body (between { and }) will be deleted (garbage collection) at the end of that method.在方法体中(在 { 和 } 之间)声明的任何变量都将在该方法结束时被删除(垃圾收集)。 (unless you asign it to something which is NOT created in the method body) (除非您将其分配给未在方法主体中创建的内容)

You're creating the variable "amount" when you run:您在运行时创建变量“amount”:

 double amount;

At this point you've created the variable but never assigned a value to it.此时,您已经创建了变量,但从未为其分配值。 The first time you use this variable is in your return statement:你第一次使用这个变量是在你的 return 语句中:

return (amount = reader.nextDouble());

What you should've done is either assign the variable on the same line as the declaration:您应该做的是在与声明相同的行上分配变量:

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

Or, better still, don't use the variable at all (although it may improve code readability, in which case a valid point could be made to keep it):或者,更好的是,根本不使用该变量(尽管它可能会提高代码可读性,在这种情况下,可以提出有效的观点来保留它):

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

        return reader.nextDouble();
    }

Why is Intellij warning me?为什么 Intellij 会警告我?
Intellij is just telling you that in the end your variable isn't being used (it isn't) so it's safe to remove the variable declaration. Intellij 只是告诉您,最终您的变量没有被使用(不是),因此删除变量声明是安全的。

Intellij should however also provide you with a solution like I just did if you hover over the little lightbulb which appears at the start of your line of code.但是,如果您将鼠标悬停在出现在代码行开头的小灯泡上,Intellij 也应该为您提供一个解决方案,就像我刚才所做的那样。 An example:一个例子: 在此处输入图片说明

它告诉您,您可以简单地返回reader.nextDouble()并且您不需要为此目的的可变amount

Because you aren't doing anything with it.因为你没有用它做任何事情。 The code could be simplified to:代码可以简化为:

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

you can just do你可以做

 return reader.nextDouble();

That variable declaration and assignment are taking up memory.那个变量声明和赋值占用了内存。

Try turning Inspection Mode off for redundant local variables.尝试关闭冗余局部变量的检查模式。 Or you can just simply do :或者你可以简单地做:

return reader.nextDouble();

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

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