如何在Java中将字符串转换为int
我正在研究Caesar密码示例,其中我希望它从用户处获得不同的密钥,最后一个密钥解密原始文本,但我遇到了一个问题,这是我的代码如何在Java中将字符串转换为int,java,string,int,Java,String,Int,我正在研究Caesar密码示例,其中我希望它从用户处获得不同的密钥,最后一个密钥解密原始文本,但我遇到了一个问题,这是我的代码 public static void main(String[] args) { Scanner user_input= new Scanner(System.in); String plainText = "University of malakand"; String key; key = user_input.next();
public static void main(String[] args) {
Scanner user_input= new Scanner(System.in);
String plainText = "University of malakand";
String key;
key = user_input.next();
Ceasercipher cc = new Ceasercipher();
String cipherText = cc.encrypt(plainText,key);
System.out.println("Your Plain Text :" + plainText);
System.out.println("Your Cipher Text :" + cipherText);
String cPlainText = cc.decrypt(cipherText,key);
System.out.println("Your Plain Text :" + cPlainText);
}
它在这行上显示一个错误
String cipherText = cc.encrypt(plainText,key);
它显示键不兼容类型的错误:
无法将字符串转换为int
我能做什么?似乎需要将字符串转换为int,而不是int转换为String。为此,可以使用Integer.parseInt: 试试这个-
String cipherText = cc.encrypt(plainText,Integer.parseInt(key));
您正在传递字符串,并且方法参数似乎有int,因此出现了错误。您可能希望使用int-keyInt=Integer.parseIntkey将字符串转换为int;如有必要,对纯文本也是如此,然后将keyInt和/或plainTextInt作为参数传递。首先向自己提出以下问题 你的方法想要什么作为参数? 为什么两者都不兼容? 什么字符串cipherText=cc.Encrypt明文,密钥;意思是 键是String还是int?
使用Integer.parseIntString value或Integer.ValueOfsString value等方法进行转换。首先,字符串不能转换为int对您意味着什么?您认为没有必要显示输入的值吗?
String cipherText = cc.encrypt(plainText,Integer.parseInt(key));