gpt4 book ai didi

java - 如何修复代码中的空指针异常?

转载 作者:行者123 更新时间:2023-12-02 02:58:26 25 4
gpt4 key购买 nike

我正在尝试读取一个文件并将文件中的每一行设置为我创建的对象 OS_Process 的参数,然后将这些进程放入链接列表队列中。但是,我不断收到空指针异常。数据文件如下所示。每个新的过程数据都在一个新行上。

3 //counter
1 3 6 //process 1 data
3 2 6 //process 2 data
4 3 7 //process 3 data

这是我的代码

    import java.io.*;
import java.util.*;

public class OS_Scheduler
{
public static void main(String[] args)
{
Queue<OS_Process> jobs = new LinkedList<OS_Process>();

try
{
System.out.print("Enter the file name: ");
Scanner file = new Scanner(System.in);
File filename = new File(file.nextLine());

OS_Process proc = null;
String s = null;
int a = 0, p = 0, b = 0;
BufferedReader input = new BufferedReader(new FileReader(filename));
StringTokenizer st = new StringTokenizer(s);
int count = Integer.parseInt(st.nextToken());
while ((s = input.readLine()) != null)
{
st = new StringTokenizer(s);
a = Integer.parseInt(st.nextToken());
p = Integer.parseInt(st.nextToken());
b = Integer.parseInt(st.nextToken());
proc = new OS_Process(a, p, b, 0);
jobs.add(proc);
}
input.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}

}
}

最佳答案

您遇到了 NullpointerException,因为您设置了 String s = null;,然后调用了 StringTokenizer stz = new StringTokenizer(s); 等于 StringTokenizer stz = new StringTokenizer(null); 并且这会获取 Nullpointer。

您不需要知道 count 行,因为 while 循环会迭代文件中的所有行,并且如果到达文件末尾就会停止因此请按如下方式更新您的代码:

String s = input.readLine();//read first line to get rid of it
if(s == null){
//File is empty -> abort
System.out.println("The file is empty");
System.exit(0);
}
int a = 0, p = 0, b = 0;
StringTokenizer st;
while ((s = input.readLine()) != null)
{...}

或者如果您想使用计数,您可以这样做:

String s = input.readLine();
checkReadLineNotNull(s);
int a = 0, p = 0, b = 0;
StringTokenizer st = new StringTokenizer(s);
int count = Integer.parseInt(st.nextToken());

for (int i = 0; i < count; i++) {
s = input.readLine();
checkReadLineNotNull(s);
st = new StringTokenizer(s);
//...
}

//Checks if s != null otherwise kills the programm
private static void checkReadLineNotNull(String s) {
if(s == null){
//File is empty abort
System.out.println("The file is empty");
System.exit(0);
}
}

关于java - 如何修复代码中的空指针异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42727477/

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