Home > Net >  Java - Variable name already defined in method
Java - Variable name already defined in method

Time:11-04

I'm trying to finish this debugging assignment for my intro to Java class and I believe I got most of it right as I am down to one error, here's the code.

import java.util.Scanner;
public class DebugThree3
{
   public static void main(String args[])
   {
      String name;
      name = getName(name);
      displayGreeting(name);           
   }
   public static String getName(String name)
   {
      String name;
      Scanner input = new Scanner(System.in);
      System.out.println("Enter name ");
      name = input.nextLine();
      return name;
   }
   public static void displayGreeting(String name)
   {
      System.out.println("Hello, "   name   "!");
   }
}

The error says: error: variable name is already defined in method getName(String) String name; Can anybody help me with this?

CodePudding user response:

public static String getName(String name)

This line defines a method called getName with a parameter called name.

Received parameters are effectively local variables (i.e. you address them the same way and they use the same namespace).

Then this line

String name;

tries to define a local variable with the same name. That's not allowed. There would be no way to distinguish the two.

It seems that there's actually no point in accepting the name parameter, since you seem to try to just return what the user input, so just change the method definition to look like this:

public static String getName()

CodePudding user response:

You have defined the 'name' variable in the function getName, but it is also passed in as a parameter too, which is what's causing the error.

I think from your code, you want to remove the parameter (swap public static String getName(String name) to public static String getName()) and have the user input the name instead.

You therefore also don't need to define it in main(). I therefore think your code should look like this:

import java.util.Scanner;
public class DebugThree3
{
   public static void main(String args[])
   {
      String name = getName();
      displayGreeting(name);           
   }
   public static String getName()
   {
      Scanner input = new Scanner(System.in);
      System.out.println("Enter name ");
      return input.nextLine();
   }
   public static void displayGreeting(String name)
   {
      System.out.println("Hello, "   name   "!");
   }
}
  • Related