嗨,我的 java 编码有一些问题。我不知道如何指向一个对象。
代码看起来像这样。我有两节课。用户和用户。Users 类,将用户列表作为 Linked List 进行管理,是添加、删除等操作的类。我必须编写一种方法,而不是从一个用户向另一个用户发送消息。
该方法位于 User 类中,另一个 send 方法位于 Users 类中,User 将调用该方法 - send() 以访问列表。由于用户的主要构造函数被设置为驱动整个程序。我必须编写另一个构造函数。但我被困在这里。
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();
}
}
二等
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();
}
}