我是 Java 的新手,需要您的帮助。我的导师给我上了 MD5Digest 类(class),当我自己运行文件时,它编译没有问题。但是当我将类(class)复制并粘贴到我的文件时,它不起作用。有人可以帮帮我吗?我读到它与 try catch 循环有关,但我不确定如何为这个特定的类设置一个,因为它是给我的,我不知道它的一半是什么意思。提前致谢!
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.security.MessageDigest;
public class Login{
public static void main(String []args){
Scanner user_input = new Scanner(System.in);
String entered_username = Get_Credentials.get_username(user_input);
String entered_password = Get_Credentials.get_password(user_input);
MD5Digest.encrypt(entered_password);
user_input.close();
User[] all_users = File_Scanner.create_users();
}
}
class Get_Credentials{
public static String get_username(Scanner user_input){
System.out.println("Username: ");
return user_input.next();
}
public static String get_password(Scanner user_input){
System.out.println("Password: ");
return user_input.next();
}
}
class File_Scanner{
public static User[] create_users(){
User users[] = new User[6];
int index_counter = 0;
try {
File credentials_file = new File("credentials.txt");
String pattern = "[^\"\\s]+|\"(\\\\.|[^\\\\\"])*\"";
Scanner file_reader = new Scanner(credentials_file);
while (file_reader.hasNextLine()) {
users[index_counter] = new User();
users[index_counter].username = file_reader.findInLine(pattern);
users[index_counter].encrypted_password = file_reader.findInLine(pattern);
users[index_counter].password = file_reader.findInLine(pattern);
users[index_counter].role = file_reader.findInLine(pattern);
file_reader.nextLine();
index_counter++;
}
file_reader.close();
}
catch (Exception e) {
System.out.println(e.getClass());
}
return users;
}
}
class User {
String username;
String password;
String encrypted_password;
String role;
}
class MD5Digest {
public static void encrypt(String original) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
System.out.println("original:" + original);
System.out.println("digested:" + sb.toString());
}
}
抛出的错误:
Login.java:12: error: unreported exception Exception; must be caught or declared to be thrown
MD5Digest.encrypt(entered_password);
^
1 error
最佳答案
您使用的是什么 IDE?您应该能够轻松解决此错误,而无需任何外部帮助。在 IntelliJ 上按 Alt + Enter 可以选择将加密方法调用包含在 try/catch block 中,如下所示:
try {
MD5Digest.encrypt(entered_password);
} catch (Exception e) {
e.printStackTrace();
}
该方法会抛出异常,这基本上意味着它可能会遇到错误,而 try catch block 是一种在不让程序崩溃的情况下处理该错误的方法。
加密方法位于底部,在 MD5Digest 类中。查看第一行:
public static void encrypt(String original) throws Exception
它告诉编译器它可能会遇到异常(错误),您应该准备好处理这种可能性。因此需要 try/catch。它将尝试 try 括号中的内容,然后如果遇到错误,将执行 catch block 中的代码。
关于java - 什么是异常错误,我该如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54815328/