Skip to main content
gamedev.net
🔒 Locked

Java main method

Started by chapinch 4 replies 1.2k views
Original Post
chapinch
chapinch
Hi all I cannot seem to get this code to execute in eclipse please see attached, Im very new to Java so any help would be great.

Kind Regards Chapinch[color="#ff0000"][color="#ff0000"]

import java.util. *;public class AddressBook
{

private List members = new ArrayList();

public static void main(String[] args)
{
AddressBook book = new AddressBook();
}

public AddressBook()
{
super();
this.addNewMember();
}

public List getMembers()
{
return this.members;
}

public void addNewMember()
{
String text = null;
while(!text.equals("."))
{
Scanner scan = new Scanner(System.in);
text = scan.nextLine();
Person newMember = new Person(text);
this.getMembers().add(newMember);
}
this.sortAddressBook();
}

public void sortAddressBook()
{
Collections.sort(this.getMembers());
System.out.println(this.getMembers());
}

}

import java.util.Comparator;


public class Person implements Comparable
{
private String name;
public String getName()
{
return name;
}

public Person(String name)
{
this.name = name;
}
public int compareTo(Person arg)
{
return this.getName().compareTo(arg.getName());
}
}

[color="#ff0000"][color="#ff0000"]



[color="#ff0000"][color="#ff0000"][color="#7f0055"][color="#7f0055"]

rip-off
rip-off
Are you getting it to run, or are you having trouble getting it to compile? One problem I see is in addNewMember(), you are calling a method on a null object (text). You should structure your loop such that you create the Scanner outside the loop. The loop condition could be "scan.hasNextLine()". Inside the loop body you can test if the next line equals "." and use the break keyword to exit the loop in this case.
chapinch
chapinch
Hi there



The error occurs in the main method is "cannot make a static reference to a none static field" refereing to the new addressBook variable, the error happens at compile time.



Kind regards Chapinch
rip-off
rip-off
That error cannot occur in the code as posted. I was able to get that code to compile and run with a little bit of work. If you've changed the code since, please include the latest version. Use code tags to get nice syntax highlighting.
chapinch
chapinch
Hi there



I changed my scanner declaration to outside the while loop and declared and initialised my String instead of assigning it null as you advised and the code works fine thanks matey you were a great help.



Kind regards Chapinch
dmatter
dmatter
By the way you don't need to explicitly call [font="'Courier New"]super()[/font], if you leave it out then it's implied and the compiler will automatically invoke the super class's default constructor for you; it's more conventional to just rely on this.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.