gpt4 book ai didi

java - 尝试解析数组时出现空指针异常(java)

转载 作者:行者123 更新时间:2023-12-01 23:36:03 26 4
gpt4 key购买 nike

当我尝试解析字符串数组索引时,出现空指针异常。我该如何解决?谢谢

public class studentclass {
public static void main(String[] args){

Scanner scan = new Scanner(System.in);
String[][] student = new String[10][];
Double[][] results = new Double[10][];
Double[] total = new Double[10];
String tableln = "";

for(int index = 0; index < student.length; index++){
System.out.println("\nPlease enter student " + (index+1) + "'s details");
String userinput = scan.nextLine();
student[index] = userinput.split(",");

//converts string array in to double array but receiving null pointer exception
results[index][0] = Double.parseDouble(student[index][2]);
results[index][1] = Double.parseDouble(student[index][3]);
results[index][2] = Double.parseDouble(student[index][4]);
results[index][3] = Double.parseDouble(student[index][5]);
total[index] = (results[index][0]*0.1+results[index][1]*0.4+
results[index][2]*0.3+results[index][3]*0.2);

最佳答案

看起来results[index]需要初始化。您使用 new 为 results[0..n] 分配了内存,但没有为 results[index][0...n] 分配了内存。

如果您始终存储四个值,请添加如下内容:

results[index] = new Double[4];

关于java - 尝试解析数组时出现空指针异常(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18680064/

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