Home > Software engineering >  Problems verifying the value scanned by the user (void cannot be dereferenced)
Problems verifying the value scanned by the user (void cannot be dereferenced)

Time:01-17

I'm having problems with two lines of my code, the lines are:

if (j1.setName(scr.nextLine()).isEmpty())

if (j1.setStand(scr.nextLine()).isEmpty())

The problem with these two lines is the same: void cannot be dereferenced

  • Code
package class;
import java.util.Scanner;

public class Class {

    public static void main(String[] args) {
        Scanner scr = new Scanner(System.in);
        JoJo j1 = new JoJo();
        while(true){
            System.out.print("Type your name: ");
            if (j1.setName(scr.nextLine()).isEmpty()){
                System.out.println("The name cannot be empty, redo the operation correctly.");       
            } else {
                j1.setName(scr.nextLine());
                break;
            }       
        }
        while(true){
            System.out.print("Enter the stand");
            if (j1.setStand(teclado.nextLine()).isEmpty()){
                System.out.println("The stand cannot be empty, please redo the operation correctly.");   
            } else {
                j1.setStand(scr.nextLine());
                break;
            }  
        }
        j1.interaction();
    }
}

CodePudding user response:

You don't show the JoJo class, but it likely has a setter method for setName(...) that returns void (as it should). And so this:

if (j1.setName(scr.nextLine()).isEmpty())

is where you appear to be trying to do "method chaining" where you're trying to call a method off of whatever is returned by the j1.setName(...) method.

So, if setName(...) returned the this instance of JoJo:

public JoJo setName(String name) {
    this.name = name;
    return this;
}

you'd be in luck, and this would work, but this is a bit non-standard for a setter method, and I don't recommend it, and instead recommend that you stick with a traditional setter method signature:

public void setName(String name) {
    this.name = name;
    // return this; ** Nope! **
}

and in this situation, "method chaining", where you try to call a method on an object returned from a preceding method, doesn't make sense since you'd be trying to call a method on a preceding method returns void -- and this simply won't work.

Instead, separate and simplify:

String txt = scr.nextLine().trim();
if (txt.isEmpty()) {
   System.err.println("The name cannot be empty, redo the operation correctly.");
} else {
   j1.setName(txt);
   break;
}

Same for your other attempt at method chaining.

  •  Tags:  
  • Related