gpt4 book ai didi

java - 将用户名/密码从一个类和方法传递到另一个类

转载 作者:行者123 更新时间:2023-12-02 13:39:33 26 4
gpt4 key购买 nike

我必须类,并且我需要将两个值输入到我的程序中的一个类中。

import java.io.IOException;
import java.sql.*;
import static java.lang.System.out;

public class login{

private String username;
private String password;

public void logon() throws IOException {

System.out.println("Write your Name");
username = System.console().readLine();
System.out.println(username);
System.out.println("Write your Password");
password = System.console().readLine();
System.out.println(password);

try {
// Does stuff
}
catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}

主要是在try catch中验证了用户名和密码之后。我需要将这两个字符串转移到另一个类。见下文。

    public class ClientHandler {
protected Socket client;
protected PrintWriter out;
protected String Username;
protected String Password;

public ClientHandler(Socket client) {
//Does Stuff
}
}

我想要一些关于如何实现这一目标的指示,可以通过构造函数,也可以通过任何其他有效的方法。

最佳答案

I need to transfer those two strings to another class.

您可以通过创建一个(或多个)setter 方法来做到这一点。

您需要将这两个方法添加到您的 ClientHandler 类中。

public void setPassword(String password) {
this.Password = password;
}

public void setUsername(String username) {
this.Username = username;
}

然后,您可以使用这些 setter 方法设置用户名和密码变量

ClientHandler handler = ... //Create this object somehow

handler.setUsername(username);
handler.setPassword(password);

在你的情况下,这应该放在你的“尝试” block 中

关于java - 将用户名/密码从一个类和方法传递到另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42812612/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com