简体   繁体   中英

Convert StringBuffer encryption to int

So I have a basic encryptor that after it decrypts, I want to convert the string of numbers in that file to an int.

public class Encryption {

//Basic Encryptor/Decryptor
public Encryption() throws IOException {
    StringBuffer num = new StringBuffer("100");
    encrypt(num);

    File f = new File("C:\\fun\\a");
    if(f.mkdirs()) {
    File f2 = new File(f,"b.txt");
    FileWriter fw = new FileWriter(f2);
    BufferedWriter bw = new BufferedWriter(fw); 
    bw.write(num.toString());
    bw.close();

    Scanner s = new Scanner(f2);
    String aaa = new String(s.nextLine());
    StringBuffer bbb = new StringBuffer(aaa);
    decrypt(bbb);
    int b = Integer.parseInt(aaa.toString());

    System.out.println(b);



    }

}

//ENCRYPTOR
public static void encrypt(StringBuffer word) {
    for(int i = 0; i < word.length(); i++) {
        int temp = 0;
        temp = (int)word.charAt(i);
        temp = temp * 9;
        word.setCharAt(i, (char)temp);
    }
}

//DECRYPTOR
public static void decrypt(StringBuffer word) {
    for(int i = 0; i < word.length(); i++) {
        int temp = 0;
        temp = (int)word.charAt(i);
        temp = temp / 9;
        word.setCharAt(i, (char)temp);
    }
}


public static void main(String[] args) {    
    try {
        @SuppressWarnings("unused")
        Encryption e = new Encryption();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  }

I tried to convert the string buffer to a string then an int. When I check the file, it is still encrypted and the console has an error decrypting.

Exception in thread "main" java.lang.NumberFormatException: For input string: "???"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Encryptor.Encryption.<init>(Encryption.java:28)
at Encryptor.Encryption.main(Encryption.java:62)

Which points to int b = Integer.parseInt(aaa.toString()); .

I think your only problem is that you're trying to parse the contents of the aaa StringBuffer. The aaa StringBuffer still contains the encrypted contents. You're passing the bbb buffer to the decrypt method, so that is the buffer you should attempt to parse into an int:

int b = Integer.parseInt(bbb.toString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM