-1

So, I'm trying to continue my Giraffe program (don't ask). I want users to name their giraffe and that should be the name of the giraffe. For example:

System.out.println("Name your giraffe.");

Something like:

Giraffes.somenewvariabletype scannerexample.nextLine() = Giraffes.Giraffe(parameter, parameter)

Jonathan Spirit
  • 569
  • 3
  • 7
  • 14
  • Also, giving a name to the giraffe and giving a name to a variable referencing your `Giraffe` object are two different things. – Sotirios Delimanolis Dec 15 '13 at 02:17
  • Don't put too much importance to variable names, they really have limited import in Java and in fact are almost non-existent in compiled code. Instead concentrate on object *references* -- ways of getting a handle on an object, be it with indexes in a collection or array, or via Strings in a Map. – Hovercraft Full Of Eels Dec 15 '13 at 02:19
  • 6
    The duplication link doesn't have any answers that explicitly mention it: don't do this. You can do it trough reflection, but it's such bad design. Your variable names should always be known at compile time, at the very least for intellisense. Use a `Map` if you want to link them, but never use the actual variable name. – Jeroen Vannevel Dec 15 '13 at 02:24
  • 2
    @JeroenVannevel Even with reflection, you can't dynamically set variable names and, as you said, it would be pointless to do so. – Sotirios Delimanolis Dec 15 '13 at 02:29
  • 1
    Agree with Sotirios, @JeroenVannevel, reflection won't solve this, and as you mention, even if it could, shouldn't be used to solve this non-problem. – Hovercraft Full Of Eels Dec 15 '13 at 02:31
  • Heh, you're right. I always assumed it might've been possible trough reflection but now that I actually search for it I can't seem to find a way. Maybe through one of those libraries that can compile code from a string. I'll leave a small note at the original question so this shouldn't be repeated as much. – Jeroen Vannevel Dec 15 '13 at 02:34

1 Answers1

5

Maybe you want something like this

public class Giraffe{
    String name;

    public Giraffe(String name){
        this.name = name;          // this set the name for your Giraffe object
    }

    public getName(){     // returns the name of the Giraffe object
        return name;
    }
}

Then you can use it like this

Scanner scanner = new Scanner(System.in);
System.out.println("Name your giraffe.");
String name = scanner.nextLine();     // get user input for name

Giraffe giraffe = new Giraffe(name);  // use the constructor above to set name

System.out.println(giraffe.getName());  // prints name of giraffe
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720