Hi I have some problem with my java coding. I cannot figure out how to point to an object.
The code looks like this. I have two classes. User and Users. Users class, which manages a user list as Linked List, is the class that adds, removes and so on. I have to code a method as well than sends message from one user to another user.
The method live in User class and another send method is located in Users class which will be called by User - send() to access the list. Since main constructor of Users is set to drive whole program. I have to write another constructor. But I am stuck here.
import java.util.*;
public class User
{
private String name;
private Users users;
public User()
{
this.name = readName();
}
public User(Users users)
{
this.users = users;
}
private String readName()
{
System.out.print(" Name: ");
return In.nextLine();
}
public boolean matches(String name)
{
return this.name.equals(name);
}
public String getName()
{
return this.name;
}
public void use()
{
char c = readChoice();
while (!isEnd(c))
{
execute(c);
c = readChoice();
}
}
private char readChoice()
{
System.out.print(" Choice (l/r/s/d/x): ");
return In.nextChar();
}
private boolean isEnd(char c)
{
return c == 'x';
}
private void execute(char c)
{
switch(c)
{
case 'l': look(); break;
case 'r': read(); break;
case 's': send(); break;
default : System.out.println(" Invalid choice");
}
}
private void look()
{
}
private void read()
{
}
private void send()
{
users.send();
}
}
second class
import java.util.*;
public class Users
{
public static void main(String[] args)
{
new Users();
}
private LinkedList<User> users = new LinkedList<User>();
private LinkedList<Email> emails = new LinkedList<Email>();
public Users()
{
menu();
}
private void menu()
{
char c = readChoice();
while (!isEnd(c))
{
execute(c);
c = readChoice();
}
}
private char readChoice()
{
System.out.print("Choice (a/d/g/u/x): ");
return In.nextChar();
}
private boolean isEnd(char c)
{
return c == 'x';
}
private void execute(char c)
{
switch(c)
{
case 'a': add(); break;
case 'd': delete(); break;
case 'g': break;
case 'u': use(); break;
default : System.out.println(" Invalid choice");
}
}
private void add()
{
User user = new User();
if (!exists(user.getName()))
{
users.add(user);
System.out.println(" User " + getIndex(user) + ": " +
user.getName());
}
else
System.out.println("already exists");
}
private int getIndex(User user)
{
int index = users.indexOf(user) + 1;
return index;
}
private void delete()
{
User user = user(readName());
if (user != null)
users.remove(user);
else
System.out.println(" No such name");
}
public void send()
{
}
private void use()
{
User user = new User();
if (exists(user.getName()))
user.use();
else
System.out.println(" No such user");
}
private boolean exists(String name)
{
return user(name) != null;
}
private User user(String name)
{
for (User user: users)
if (user.matches(name))
return user;
return null;
}
private String readName()
{
System.out.print(" Names: ");
return In.nextLine();
}
}