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:
Local variable 'amount' is redundant
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:
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 (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 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 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.
An example:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With