gpt4 book ai didi

字符串数组中的 java.lang.NullPointerException?

转载 作者:行者123 更新时间:2023-12-01 11:48:33 25 4
gpt4 key购买 nike

我正在学习java中的数组,并编写了一个将文本文件加载到字符串数组中的程序。然后提示用户搜索字符串。

程序编译得很好,但是当我运行它时,出现以下错误:

Exception in thread "main" java.lang.NullPointerException
at WordsArray.main(WordsArray.java:60)

第 60 行如下:

if (words[index].compareTo(words[minIndex]) > 0)

我想知道这是否与创建我的单词数组实例有关?我不确定在哪里采用这个想法(我认为给定的实例将在迭代中创建),因此欢迎提出任何建议!

这是我的代码:

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

public class WordsArray
{
public static void main(String[] args) throws IOException
{
final int NUM_WORDS = 100; // Number of words read from file
String[] words = new String[NUM_WORDS]; // Array of words
int index = 0; // Control the loop

// Open the file.
File file = new File("words.txt");
Scanner inputFile = new Scanner(file);

// Read the file contents to an array
while (inputFile.hasNext() && index < words.length)
{
words[index] = inputFile.nextLine();
index++;
}

// Close the file.
inputFile.close();

// Ask the user to search for a word
Scanner keyboard = new Scanner(System.in); // Create Scanner object
System.out.println("Enter the word to search: ");
String value;
value = keyboard.nextLine();

// Selection sort
int startScan = 0;
int minIndex;
String firstValue;

for (startScan = 0; startScan < (words.length - 1); startScan++)
{
minIndex = startScan;
firstValue = words[startScan];
for (index = startScan + 1; index < words.length; index++)
{
if (words[index].compareTo(words[minIndex]) > 0)
{
//firstValue = words[index];
minIndex = index;
}
}
words[startScan] = words[minIndex];
words[minIndex] = firstValue;
}

// Binary Search
int first; // First array element
int last; // Last array element
int middle; // Middle point of search
int position; // Position of search value
boolean found; // Flag

// Set initial values
first = 0;
last = words.length -1;
position = -1;
found = false;

// Search for the value
while (!found && first <= last)
{
// Calculate midpoint
middle = (first + last) / 2;

if (words[middle].equals(value)) // if value is in middle
{
found = true;
position = middle;
}
else if (words[middle].compareTo(value) > 0) // if value is in lower half
{
last = middle - 1;
}
else // if value is in upper half
{
first = middle + 1;
}
}

// Print index of search value, or -1 if not found
if (found = true)
{
System.out.println(value + " was found at " + position);
}
}
}

最佳答案

条件:

while (inputFile.hasNext() && index < words.length)
如果 inputFile 没有“next”,

将停止,但稍后在 for 循环中,您不会考虑输入可能在数组填满之前完成:

for (startScan = 0; startScan < (words.length - 1); startScan++)

关于字符串数组中的 java.lang.NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28954828/

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