簡體   English   中英

將用戶名/密碼從一個類和方法傳遞到另一個類

[英]Passing username/password from a class and method to another class

我必須要上課,並且需要在程序中的一個類中輸入兩個值。

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();
        }
    }
}

主要是在嘗試捕獲中驗證了用戶名和密碼之后。 我需要將這兩個字符串轉移到另一個類。 見下文。

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

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

我想要一些如何通過構造函數或任何其他有效方法來實現此目標的指針。

我需要將這兩個字符串轉移到另一個類。

您可以通過創建一個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);

就您而言,這應該放在您的“嘗試”塊中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM