我正在尝试将SQL结果中的变量分配给数组元素,但它一直向我显示java.lang.NullPointerException。我试图声明上面的数组,但似乎不起作用。异常未显示错误所在的行,但是我编写了打印语句以找出异常的位置,然后发现当我打印activity[i]
的值时,它等于null
。
这里是代码:
package main;
import java.awt.EventQueue;
public class ACTIVITY {
private Connection con;
private Statement stm;
private String sql;
private ResultSet rs;
private static int c_id=-1;
private static int s_id=-1;
private int a_id=-1;
private String activity[]=new String[5];
private int activityID[] =new int[5];
public static JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ACTIVITY window = new ACTIVITY();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ACTIVITY() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null);
panel.setVisible(true);
try {
Class.forName("com.mysql.jdbc.Driver");
con=
DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","****" , "********");
stm= con.createStatement();
sql="Select * from activity where sid="+s_id;
rs=rs=stm.executeQuery(sql);
String name=" ";int i=0;
while(rs.next()){
name=rs.getString("a_name");
a_id=rs.getInt("a_id");
activity[i]=name;//after this assignment it always equal null
activityID[i]=a_id;
i++;
}
//the rest of the code
con.close();
} catch(Exception e) {System.out.println(e); }
}
}
个人,我建议为此使用ArrayList而不是数组,但这只是个人喜好。这是关于https://www.w3schools.com/java/java_arraylist.asp
的文章就您所遇到的问题而言,问题是您已声明一个私有字符串数组,并试图通过另一种方法为其分配值。由于该数组是一个String数组,因此其默认值为null。您收到异常的原因是因为它返回此默认值,而不是您分配的值。
您仍然可以使用私有数组,但是您需要将其声明为静态数组,并使用静态方法为其添加值。这样,当您将值添加到它时,它将以您期望的方式返回。这是一个简单得多的示例,但显示了如何实现此目的:
public class Test {
private static String activity[] = new String[5];
public void addValue() {
activity[0] = "Yo";
}
public static void main(String[] args) {
Test test = new Test();
test.addValue();
System.out.println(activity[0]);
}
}
关于您的特定代码,我建议将activity []和activityID []都声明为静态数组。然后,您将需要在main方法中创建一个对象以调用您的值。您所做的更改如下所示:
private static String activity[] = new String[5];
private int activityID[] =new int[5];
然后在您的主要方法中,添加:
window.initialize(); //where window is your class object you declared
将为您带来所需的结果。我还建议重命名与类调用相同方法的方法。