-2

I've declared a Scanner object and I want a method the sets the name of the Scanner. I thought about something like this:

public static void ScannerSetUp(String ScannerName) {
        Scanner ScannerName = new Scanner(System.in);
    }

But I get a message saying that the variable is already defined in the scope. Does anybody know how to do it?

Thank you.

  • 1
    You are using the samme parameter name ‘ScannerName’ as your lokal variable in your method body. Therefore the Java compiler cannot separate these two variable names from each other. Therefore you should rename one of these variable names – Guldborg92 Jun 07 '20 at 10:06
  • But that would not set the variable name with which I could call the Scanner, and the method would be useless. – cristiano ronaldo Jun 07 '20 at 10:33
  • In my option, what you are trying to do is completely pointless. You name a variable so that the name is relevant and possibly explains the use of the variable for yourself and others when reading the code. To have specific names for a variable at runtime makes no sense and isn't useful to anyone. – Joakim Danielson Jun 07 '20 at 10:40
  • There is no way to name an object at all, let alone as you require. Are you looking for a Map? – user207421 Jun 07 '20 at 11:14
  • Evidently you want to set the name of an object to something decided at runtime. But, in that case, no compile-time element can use that name. So if you manage to give a name to this object at runtime, what is going to use that name? – arcy Jun 07 '20 at 11:17

1 Answers1

0

In java when you defined some variable inside the method parameters(these variables are also local variables but if you want to be more specific you can call these variables as parameterized variables or arguments ) or within a method we called them as local variables. So these variables have their life time only within the scope (Scope means the closest curly braces they are surrounded with) So in here you are trying to define two local variables within the same scope with the same name,so that's why you are getting that compile time error.

SOLUTION: But regarding what you are trying to it's completely useless because you are trying to assign new variable name in the runtime it's totally useless and I don't think it will be possible to do like a language with java which is not using dynamic variables.

Best practices: Try to use camel case to define variables ---->scannerName would be better.

Hasindu Dahanayake
  • 1,344
  • 2
  • 14
  • 37