gpt4 book ai didi

java - 将字符串分配给 stringArray 时返回 NullPointerException?

转载 作者:行者123 更新时间:2023-11-30 06:15:31 25 4
gpt4 key购买 nike

我可以看到 sysOut 中的值,但它仍然返回 nullPointer 异常。我做错了什么?

    class ProjUtils {

int noSteps;
String testName="";
String DMS;
String appL;
String func;
String subFunc;
String desc="";
String regPriority = "High||Medium||Low";
String type = "Manual||Automated";
String[] stepName ;
String[] stepDesc ;
String[] expRes ;
int counter=1;
int caseCounter = 1;

public void preDefSteps() {


System.out.println("Enter number of predefined steps:");

String stName = null,stDesc = null,expResu = null;

try {

noSteps = Integer.valueOf(br.readLine());
int i =0;

while(i<noSteps && br.readLine() !=null){

br.readLine();

System.out.println("Step Name:\n");
stName = br.readLine();
System.out.println("Step Descripiton:\n");
stDesc = br.readLine();
System.out.println("Expected Result:\n");
expResu = br.readLine();
br.readLine();
System.out.println(stName + "\n" + stDesc + "\n" + expResu);
stepName[i] = stName;
stepDesc[i] = stDesc;
expRes[i] = expResu;

i++;
}

O/P: java.lang.NullPointerException at testCaseAuto.ProjUtils.preDefSteps(ProjUtils.java:199) at testCaseAuto.ProjUtils.newConfig(ProjUtils.java:82) at testCaseAuto.Home.main(Home.java:29)

最佳答案

你的

String[] stepName ;
String[] stepDesc ;
String[] expRes ;

已声明,但未初始化。实际上它们是null。所以你不能用

给它们赋值
stepName[i] = stName;

等等。

请初始化它们,例如String[] stepName = new String[5];

对于数组初始化,您需要知道数组的大小。看来在节目结束之前你其实并不认识他们。所以也许 ArrayList 类更适合您的情况:

List<String> stepNameList = new ArrayList<>();
[...]
stepNameList.add(stName);

因此您的代码应如下所示(无需额外优化):

package code;

import java.util.ArrayList;
import java.util.List;

class ProjUtils
{

int noSteps;
String testName = "";
String DMS;
String appL;
String func;
String subFunc;
String desc = "";
String regPriority = "High||Medium||Low";
String type = "Manual||Automated";
List<String> stepNameList = new ArrayList<>();
List<String> stepDescList = new ArrayList<>();
List<String> expResList = new ArrayList<>();
int counter = 1;
int caseCounter = 1;

public void preDefSteps()
{


System.out.println("Enter number of predefined steps:");

String stName = null, stDesc = null, expResu = null;

try
{

noSteps = Integer.valueOf(br.readLine());
int i = 0;

while (i < noSteps && br.readLine() != null)
{

br.readLine();

System.out.println("Step Name:\n");
stName = br.readLine();
System.out.println("Step Descripiton:\n");
stDesc = br.readLine();
System.out.println("Expected Result:\n");
expResu = br.readLine();
br.readLine();
System.out.println(stName + "\n" + stDesc + "\n" + expResu);
stepNameList.add(stName);
stepDescList.add(stDesc);
expResList.add(expResu);

i++;
[...]
}

关于java - 将字符串分配给 stringArray 时返回 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49293730/

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