我编写了名称排序程序,用于对名称列表(duh)进行排序,并给出我姓名的索引值。由于某种原因它编译得很好,但是说'maleNames [i] = nameScan.nextLine();“并返回此消息:
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at NameSorter.main(NameSorter.java:14)
任何想法或修复?提前谢谢!
import java.io.*;
import java.util.Scanner;
public class NameSorter
{
public static void main(String [] args) throws FileNotFoundException
{
String [] maleNames = new String[1220];
PrintStream ps = new PrintStream("sorted_male_names.txt");
Scanner nameScan = new Scanner(new File("common_male_names.txt"));
for (int i = 0; i < maleNames.length; i++)
{
maleNames[i] = nameScan.nextLine();
}
bubbleSort(maleNames);
for (int i = 0; i < maleNames.length; i++)
{
System.out.println(maleNames[i]);
}
for (int i = 0; i < maleNames.length; i++)
{
String currentName = maleNames[i];
ps.println(currentName);
}
System.out.println(linearSearch(maleNames, "zander"));
}
public static boolean isSorted(String[] arr)
{
for (int i = 0; i < arr.length -1; i++)
{
if (arr[i].compareTo(arr[i+1]) > 0)
return false;
}
return true;
}
public static void swapElements(String[] arr, int index1, int index2)
{
String tempValue = arr[index1];
arr[index1] = arr[index2];
arr[index2] = tempValue;
}
public static void bubbleSort(String[] arr)
{
while(isSorted(arr) == false) // while(!isSorted(arr))
{
for (int i = 0; i < arr.length - 1; i++)
{
if (arr[i].compareTo(arr[i+1]) > 0)
swapElements(arr, i, i+1);
}
}
}
public static int linearSearch(String[] arr, String name)
{
for (int i = 0; i > arr.length; i++)
{
if (arr[i].equals(name))
return i;
}
return -1;
}
public static void printArray(int[] arr)
{
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
}
答案 0 :(得分:2)
你的for循环
for (int i = 0; i < maleNames.length; i++) {
maleNames[i] = nameScan.nextLine();
}
假设文件中有maleNames.length
个元素(在这种情况下为1220),如果少于NoSuchElementException
更好的方法是使用扫描仪的hasNextLine()
方法和List<String>
List<String> maleNames = new ArrayList<>();
while(nameScan.hasNextLine()) {
maleNames.add(nameScan.nextLine());
}
这将允许任何长度的名称文件,只要其格式正确,并避免您的异常。