我是java的新手,目前正在攻读本科编程课程。我已经获得了一项任务,要求我创建和加密类,然后是测试人员类。在tester类中,我将创建加密类的两个对象:一个使用默认构造函数,另一个使用参数化构造函数,使用两个扫描程序输入作为参数(密码和密钥)。这就是我遇到的困难。我不认为我这样做是正确的。这是代码。我编译它时收到的错误是“不兼容的类型,String不能转换为int”。我感谢任何可以帮助我的人。
public class Encryption
{
private int key;
private String encryptedPassword;
Scanner scan = new Scanner(System.in);
public Encryption()
{
key = 0;
encryptedPassword = "";
}
public Encryption(int key, String password)
{
this.key = key;
password = password;
setPassword(password);
}
public void encrypt(String password)
{
char ch;
for(int i=0; i<password.length(); i++){
ch = password.charAt(i);
if (ch >= '!' && ch <= 'z'){
ch = (char)(ch + key);
if (ch > 'z'){
ch = (char)(ch - 'z' + '!' - 1);}
else if (ch < '!'){
ch = (char)(ch +'z' - '!' +1);}
encryptedPassword = password + ch;
}
}
}
public boolean isValidPassword (String password)
{
encrypt(password);
if (password.equals(encryptedPassword))
return true;
else
return false;
}
public String getEncryptedPassword()
{
return encryptedPassword;
}
public void setPassword(String password)
{
encrypt(password);
}
public int getKey()
{
return key;
}
public String toString()
{
return "The encrypted password is " + getEncryptedPassword() + ". " + "The key used to generate this password is " + getKey() + ".";
}
}
这是测试人员类代码。
import java.util.Scanner;
public class EncryptionTester
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a password.");
String password = scan.next();
while (password.length() < 8)
{
System.out.println("The password must be at least 8 characters long. Your password is only " + password.length() + " characters long.");
System.out.println("Enter a password.");
password = scan.next();
}
System.out.println("Enter a number between 1 and 10.");
int key = scan.nextInt();
while (key < 1 || key > 10)
{
System.out.println("The key must be between 1 and 10. You entered " + key);
System.out.println("Enter a number between 1 and 10");
key = scan.nextInt();
}
Encryption defaultEncryption = new Encryption();
Encryption argEncryption = new Encryption(password, key);
}
答案 0 :(得分:2)
您正在将构造函数调用为
new Encryption(password, key);
声明时
public Encryption(int key, String password)
您需要按参数列表中指定的顺序传入参数。尝试
new Encryption(key, password);