gpt4 book ai didi

java - Java 对象创建中的未知错误

转载 作者:行者123 更新时间:2023-12-01 08:51:34 25 4
gpt4 key购买 nike

我尝试编写一个程序来使用 OOP 加密字符串,但由于某种原因,当我尝试运行仅创建其中一个对象的程序时,我总是收到此错误。

Exception in thread "main" java.lang.NullPointerException
at encryptionproject.Cipher12.<init>(Cipher12.java:8)
at encryptionproject.TestExample.main(TestExample.java:7)
C:\Users\22849\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

对象等级:

    public class Cipher12 {

public String key1;
public String ciphertext;
public String plaintext;
public int[] ikey = new int[key1.length()];
public int[] ictext = new int[plaintext.length()];
public int[] iptext = new int[plaintext.length()];

public void setKey(String key) {
this.key1 = key;
}

public void setPlaintext(String plaintext) {
this.plaintext = plaintext;
}

public void setCiphertext(String ciphertext) {
this.ciphertext = ciphertext;
}

public String getKey() {
return key1;
}

public String getCiphertext() {
return ciphertext;
}

public String getPlaintext() {
return plaintext;
}

public void convert(String s, int[] i) {
for (int j = 0; j < s.length(); j++) {
i[j] = (int) s.charAt(j);
}
}

public void convert(int[] i, String s) {
for (int j = 0; j < s.length(); j++) {
s += (char) i[j];
}
}

public void encrpty() {
convert(key1, ikey);
convert(plaintext, iptext);
ictext = iptext;
for (int j = 0; j < ictext.length; j++) {
ictext[j] -= 31;
ictext[j] -= ikey[1];
ictext[j] *= ikey[2];
ictext[j] += 2 * ikey[3];
ictext[j] -= (ikey[0] + ikey[1] + ikey[2] + ikey[3]);
ictext[j] += j * j;
while (ictext[j] > 95) {
ictext[j] -= 95;
}
ictext[j] += 31;
}
convert(ictext, ciphertext);
}

public void decrypt() {
convert(key1, ikey);
convert(ciphertext, ictext);
iptext = ictext;
for (int j = 0; j < iptext.length; j++) {
iptext[j] -= 31;
iptext[j] -= j * j;
iptext[j] += (ikey[0] + ikey[1] + ikey[2] + ikey[3]);
iptext[j] -= 2 * ikey[3];
iptext[j] /= ikey[2];
iptext[j] += ikey[1];
while (iptext[j] > 95) {
iptext[j] -= 95;
}
iptext[j] += 31;
}
convert(iptext, plaintext);
}
}

应用类:

public class TestExample {

public static void main(String[] args) {

Cipher12 t = new Cipher12();

}

}

有人可以帮我看看问题出在哪里吗?以及如何修复它?

最佳答案

key1 默认初始化为 null。初始化ikey时,调用key1.length(),key1为null,因此抛出NPE。

public String key1;
public int[] ikey = new int[key1.length()];

请提供一个以 key1 作为参数的构造函数,并在构造函数中初始化所有属性。

关于java - Java 对象创建中的未知错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42366215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com