简体   繁体   中英

Why does this program give an error when run

Can someone tell me why, when I run the program shown below, I get an error (shown below code)

public class Main{
  Node next = null;
  int data;

  public void Node(int d) {
    data = d;
  }

  void appendToTail(int d) {
    Node end = new Node(d);
    Node n = this;
    while (n.next != null) {
        n = n.next;
    }
    n.next = end;
  }
}

Node node1 = new Node(5);

node1.appendToTail(7);

I got this error that said something about class, enum, or interface expected. Can someone explain what this means and what I have to do to my code?

Main.java:19: error: class, interface, or enum expected
Node node1 = new Node(5);
^
Main.java:21: error: class, interface, or enum expected
node1.appendToTail(7);
^
2 errors
compiler exit status 1

Based on what you provided. It looks like you are trying to create linked list.

There are several issues with the program

  1. Name of the class needs to be Node instead of Main otherwise node1.appendToTail(17) will not work
  2. Lines of code outside a class , interface or enum .
Node node1 = new Node(5);
node1.appendToTail(7);

These lines must be inside any of the above three mentioned. For this question, it must be inside the main method of Node class.

  1. Constructor doesn't have a return type.
  public Node(int d) {
    data = d;
  }

Final Result

class Node {
  int data;
  Node next;

  public Node(int d) {
    data = d;
  }

  void appendToTail(int d) {
    Node end = new Node(d);
    Node n = this;
    while (n.next != null) {
        n = n.next;
    }
    n.next = end;
  }

  public static void main(String[] args) {
    Node node1 = new Node(5);
    node1.appendToTail(7);   
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM