在 Main 函数中调用 toString 方法

Calling toString method in Main function

我有 3 个不同的 类。我必须通过使用 BufferedReader 但使用 toString 方法来获取用户输入。下面是我的 User2(类 之一)中的代码。

如何在 main 函数中调用用户在 toString 中输入的所有内容?如果我必须使用对象,怎么办?

//in User2 class
@Override
public String toString() {
    try {
        //getting input using BufferedReader

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter customer name: ");
        this.name = br.readLine();
        System.out.print("Enter customer address: ");
        this.address = br.readLine();
        System.out.print("Enter customer contact no: ");
        this.hp = br.readLine();
    } catch (IOException e) {
        return "";
    }
return "" ;
}

我只知道使用

将所有内容打印成字符串
 System.out.println(u2.toString());

提前致谢。

调用 toString() 方法时不应定义对象,尤其是当您使用 Scanner 从 System.in 读取数据时。相反,当您读取数据时,您应该使用数据来实例化对象。我没看过你的布局类,但我感觉你没有完全理解what Objects are.

下面Class定义了一个User;用户有姓名、地​​址和 hp。获得此信息后,您可以创建一个新的用户对象,因为在这种情况下,拥有一个不代表已知用户的对象是没有意义的。

toString() 方法已被重写,它生成一个代表对象描述内容的字符串 - 当对象转换为细绳。 Read more about the toString method and it's purpose.

static User userFromInput() 方法可以满足您的需求。由于它是 static,您可以在 Class 上调用它,这意味着您不必实例化对象。此方法接受用户的输入(姓名、地址和 hp),实例化一个新的用户对象并 returns 它。

 public class User {
    private String name;
    private String address;
    private String hp;

    public User (String name, String address, String hp) {
        this.name = name;
        this.address = address;
        this.hp = hp;
    }

    @Override
    public String toString() {
        return name + " : " + address + " : " + hp;
    }

    public static User userFromInput() {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {

            System.out.print("Enter customer name: ");
            String name = br.readLine();
            System.out.print("Enter customer address: ");
            String address = br.readLine();
            System.out.print("Enter customer contact no: ");
            String hp = br.readLine();

            return new User(name, address, hp);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

因此,您应该要求用户输入数据,然后使用以下行将对象打印到控制台:

User user1 = User.userFromInput();
System.out.println(user1.toString());