-2

I am trying to invoke a set method in a constructor that accepts user input to instantiate an object. A sample of a set method is as follows:

public void setName(String name) {
    if(name.length()>0 && name.length()<25) {
        this.name = name;
    }
    else {System.out.println("Name length can not exceed 25 characters.");}
}

I then want to accept the user input to instantiate the object. I currently have it formatted like so:

public Character(String name){ name = setName(input.nextLine());}

I have imported the scanner and created a scanner object. The character constructor itself is actually quite large, it consists of 29 variables, each of which have a set method similar to the first code sample.

My ultimate goal is to put this in a GUI form for a person to fill out. The error Eclipse gives for my current syntax is "type mismatch, cannot convert from void to String".

How is this supposed to be done?

SPerez
  • 1
  • 1
  • The issue is here: `name = setName` because `setName` is a `void` method it does not return anything. Why would you need `setName` to return the `name` anyway? A setter does exactly that - it sets the variable. You're basically mixing a setter with a getter here and it's unclear why. – D.B. Oct 08 '18 at 03:35
  • Look at `public void setName(String name) {` - what is this telling about what the method will return? – MadProgrammer Oct 08 '18 at 03:41
  • Your constructor accepts a `name` argument and _also_ accepts a name as input??? That paradox aside, accepting input in a constructor is never a good idea. – Kevin Anderson Oct 08 '18 at 03:46
  • And don't use names that are part of the standard Java, such as Character! – GhostCat Oct 08 '18 at 04:55

1 Answers1

-1

The easiest approach is to modify your code like this:

public String setName(String name) {
    if(name.length()>0 && name.length()<25) {
        this.name = name;
    }
    else {System.out.println("Name length can not exceed 25 characters.");}
    return name;
}
  • What is the point in having a setter method return the field it just set? I don't think this is a good approach, rather you should guide the OP to use a setter properly. – D.B. Oct 08 '18 at 03:41