Java 'constructor in class cannot be applied t

2020-04-14 09:31发布

问题:

I'm working on an assignment where I have to create a linked list from scratch and have come across an error when compiling that the "constructor Node in class Node cannot be applied to given types;"

This is what I'm trying, the error says:

required: no arguments found: string

Yet I cannot see where I am going wrong as my constructor for Node requires a string?

public class Node {
    String data;
    Node next;

    public void Node(String x) {
        data = x;
        next = null;
    }
}



public class stringList {
    private Node head;
    private int count;

    public void stringList() {
        head = null;
        count = null;
    }

    public void add(String x) {
        Node temp = new Node(x);
    }

This is a screenshot of the error the compiler is showing

回答1:

This:

public void Node(String x) {
    data = x;
    next = null;
}

should be:

   public Node(String x) {
        data = x;
        next = null;
    }

Currently you have a default constructor (taking no arguments), which is implicitly defined in the absence of any explicit constructors.



回答2:

Constructors don't have a return type. What you have now is a method named Node, which returns nothing.To fix, replace this

public void Node(String x){

with

public Node(String x){