gpt4 book ai didi

java - 搜索数组时出现 NullPointerException 错误

转载 作者:行者123 更新时间:2023-11-30 09:01:00 25 4
gpt4 key购买 nike

我正在尝试运行这段代码。它成功读取文件,但在单词搜索本身中断。

错误:

Exception in thread "main" java.lang.NullPointerException
at WordSearch.main(WordSearch.java:30)

代码如下:

import javax.swing.JOptionPane;
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;


public class WordSearch{

public static void main(String[] args) throws FileNotFoundException{

String searchWord, fileName; int i=0, j=0;

fileName = JOptionPane.showInputDialog(null, "Please enter the name of the file to be processes: ");
File textFile = new File(fileName);

Scanner scanner = new Scanner(textFile);

String[] file = new String[500];
String[] found = new String[500];

while(scanner.hasNextLine()){
file[i]=scanner.next();
i++;
}

file[i+1]="EoA"; i=0;

searchWord = JOptionPane.showInputDialog(null, "Please input the string to search for: ");

while(!file[i].equals("EoA")){
if (file[i].equals(searchWord)){
if(i==0){
found[j]=file[i]+file[i+1]+"\n";
}
else if(i==500){
found[j]=file[i-1]+file[i]+"\n";
}
else {
found[j]=file[i-1]+file[i]+file[i+1]+"\n";
}

j++;
}
i++;
}

JOptionPane.showMessageDialog(null, found);
}
}

最佳答案

改变

file[i+1]="EoA";

file[i]="EoA";

否则,您将在“EoA”条目之前的位置有一个空条目,这会导致 NullPointerException

当然,您可以删除“EoA”条目,只需将循环条件更改为:

while (file[i] != null)

这更具可读性。

最后一件事,您如何保证您的输入不会大于数组的 500 长度?

关于java - 搜索数组时出现 NullPointerException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26534173/

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