名称分类器返回-1?

时间:2014-11-14 00:54:34

标签: java debugging sorting

写了名称排序程序,用于对名称列表(duh)进行排序,并给出我姓名的索引值。它应该返回1219左右,因为我的名字在列表的最后一个附近,而是返回-1?我的linearSearch方法有什么问题?

    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] + " ");
        }
    }
}

提前致谢!

1 个答案:

答案 0 :(得分:2)

更改

for (int i = 0; i > arr.length; i++)

for (int i = 0; i < arr.length; i++)