[英]NumberFormatException with Simple Encryption
package codeCracker;
public class CodeCracker {
private String encrypt;
private int encry;
public CodeCracker(String encryptmelong) {
encrypt = encryptmelong;
}
public String idolnum() {
String in;
in = encrypt;
in = in.replaceAll("\\D+", "");
encry = Integer.valueOf(in);
encrypt = encrypt.replace(in, "");
// System.out.println(encry);
return in;
}
public String encrypt() {
// encrypt+=encry;
String encrypted = "";
String charen = "";
for (int i = 0; i < encrypt.length(); i++) {
charen += encrypt.charAt(i);
// System.out.println(charen.charAt(i));
}
for (int i = 0; i < charen.length(); i++) {
System.out.println(encry);
int temp = Integer.parseInt(idolnum());
System.out.println("" + temp + " " + (int) encrypt.charAt(i));
temp = (int) encrypt.charAt(i) + temp;
encrypted = encrypted + (char) temp;
// System.out.println(encrypted.charAt(i));
}
return encrypted;
}
public String toString() {
return encrypt();
}
public static void main(String[] args) {
CodeCracker code = new CodeCracker("5 encryptme");
System.out.println(code);
}
}
我有一個關於加密的問題。 該程序應該接收一個字符串和一個數字,並通過此數字增加每個字符。 這是行不通的。 它正確接收數字,但未正確添加字符。 我還在線程“ main”中收到異常錯誤:對於輸入字符串:“”
Exception in thread "main" java.lang.NumberFormatException: For input string: "" at
Java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at
java.lang.Integer.parseInt(Integer.java:504) at
java.lang.Integer.valueOf(Integer.java:582) at
codeCracker.CodeCracker.idolnum(CodeCracker.java:15) at
codeCracker.CodeCracker.encrypt(CodeCracker.java:34) at
codeCracker.CodeCracker.toString(CodeCracker.java:44) at
java.lang.String.valueOf(String.java:2854) at
java.io.PrintStream.println(PrintStream.java:821) at
codeCracker.CodeCracker.main(CodeCracker.java:50)
不是很好:
for (int i = 0; i < charen.length(); i++) {
System.out.println(encry);
int temp = Integer.parseInt(idolnum());
System.out.println("" + temp + " " + (int) encrypt.charAt(i));
temp = (int) encrypt.charAt(i) + temp;
encrypted = encrypted + (char) temp;
// System.out.println(encrypted.charAt(i));
}
您在for循環中多次調用idolnum()
,包括從原始String中提取數字String之后,因此,當第二次這樣做時,您將獲得NumberFormatException
嘗試解析“”。 而不是這樣做,只在一次for循環之前調用diolnum()
一次。 然后,在需要加密int時使用encry int。
請注意,如果這是我的項目,那么我將以不同的方式組織它。 我只將加密int傳遞給該類,然后允許它加密和解密傳遞給它的任何字符串。 例如:
public class MyCodeCracker {
private int encry;
public MyCodeCracker(int encry) {
this.encry = encry;
}
public String encrypt(String text) {
// use encry to do encrytion
return ""; // return encrypted text
}
public String decrypt(String encryptedText) {
// use encry to translate encryptedText to text
return ""; // return text
}
public int getEncry() {
return encry;
}
public static void main(String[] args) {
// here get user input
// extract out the encryption int
// create MyCodeCracker with the int
// and then encrypt and decrypt text as needed
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.