所以我已经看了很多关于类、引用文献和方法、设置和获取的帖子几天了。我似乎无法理解这一切是如何运作的。
免责声明是的,这是为了类作业,下面这个糟糕的例子是为了说明。我将非常感谢您的帮助。
我已经有了一个正在运行的程序(尽管非常基本且效率低下)。然而,我所拥有的一切都在我的 Primary 类的主要方法中,我需要将其中的一部分放在一个单独的类中,并使其仍然有效。
使用 main 方法,用户输入明文密码 (clearText),其中提供的代码片段将密码散列到 (hashText)。然后用于其他事情。
我希望完成的是将散列密码的代码片段从我的主类的主要方法中分离出来,放入一个单独的辅助类中。
我不知道如何做到这一点。如何将clearText导入到二级类中,然后将hashText输出回主类中的main方法。
谢谢。
import java.util.*;
import java.io.*;
public class Primary {
public static void main(String[] args) throws Exception {
String clearText = ("");
System.out.print("Type Text");
clearText = scnr.next();
//Somehow export clearText to the secondary class
//Somehow import hashText into the main method for further use
System.out.println(hashText);
}
}
public class Secondary {
String hashText = ("");
//Somehow import clearText value inputted but the user
//here is where clearText gets hashed(I have that)
//Somehow export hashText for use in the main method
}
最佳答案
欢迎来到编程。这里需要考虑的一件事是,您似乎认为您的Secondary 类是一个不可变的实体,并且与您的程序一起运行。事实并非如此。您正在创建一个对象,其中包含您想要在程序中其他地方使用的数据和功能。
您的辅助对象可以被实例化,然后用于执行任务。您也可以通过在基类内部创建的另一个方法来执行此操作,但这也必须是静态的。
我在包含哈希实例的辅助类中没有看到太多意义,并且该问题已经得到解答。我建议您考虑将其创建为服务。
import java.util.*;
import java.io.*;
public class Primary {
public static void main(String[] args) throws Exception {
String clearText = ("");
// Collect user input
System.out.print("Type Text");
clearText = scnr.next();
// Create hash and display
String hashText = HashService.generateHash(clearText);
System.out.println(hashText);
}
}
public class HashService {
public static String generateHash(String fromText){
// implementation here
return null;
}
}
编辑:看起来有人删除了对象答案。如果您出于某种原因想要将散列密码维护为对象,您可以这样做
import java.util.*;
import java.io.*;
public class Primary {
public static void main(String[] args) throws Exception {
String clearText = ("");
// Collect user input
System.out.print("Type Text");
clearText = scnr.next();
// Create hash and display
HashedPassword hash = new HashedPassword(clearText);
String hashText = hash.getHashedPW();
System.out.println(hashText);
}
}
public class HashedPassword {
private String hashedPW = ""
public HashedPassword(String fromText){
// Assign hashedPW with some logic
hashedPW = fromText;
}
public getHashedPW(){
return hashedPW;
}
}
关于Java将变量传递给类返回不同的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53781832/