You want to create and manage a class that declares a character variable and a class that you output.
By the way, variables are imported well, but if you only try to import strings, it's a problem.
I'm attaching a simple example of the problematic part below.
Thank you.
// Output Responsible Class
package test;
public class test {
test(){
for (int i=0;i<var.size;i++)
{
System.out.println(var.txt[i]);
}
}
public static void main(String[] args) {
new test();
}
}
// Variable Management Class
package test;
public class var {
public final static int size = 5;
public static String txt[];
public var() {
txt = new String[size];
for (int i=0;i<size;i++)
{
txt[i] = new String();
txt[i] = "abcd"+i;
}
}
}
java
Exception in thread "main" java.lang.NullPointerException
at test.test.<init>(test.java:13)
at test.test.main(test.java:18)
The var.txt
value was created to be assigned by the var()
constructor, but the problem is caused by the var()
constructor not being called.
Calling the var()
constructor explicitly before accessing var.txt
resolves the issue:
test() {
new var(); // <-- Here
for (int i = 0; i < var.size; i++) {
System.out.println(var.txt[i]);
}
}
In fact, it is a very strange code for non-static members to initialize static members. Initialize with static block as shown below:
public class var {
public final static int size = 5;
public static String txt[];
static { // <--
txt = new String[size];
for (int i = 0; i < size; i++) {
txt[i] = new String();
txt[i] = "abcd" + i;
}
}
public var() {}
}
© 2024 OneMinuteCode. All rights reserved.