我想對input.txt文件進行排序並將其保存在output.txt中。我使用插入排序算法。現在我的問題:compareTo方法似乎工作不正確(或至少不是我想如何工作)。它返回大於1的整數,因此該算法對於負數不是特別重要。我希望你們能幫助我解決這個問題,謝謝!compareTo無法正常工作
那是我的代碼:
import java.util.ArrayList;
import java.io.*;
class Isort
{
public static void main(String[] args)
{
if(args[0].equals("int"))
{
ArrayList<Integer> array = new ArrayList<Integer>();
sort(array, args[1], args[2]);
}
else if(args[0].equals("float"))
{
ArrayList<Float> array = new ArrayList<Float>();
sort(array, args[1], args[2]);
}
else if(args[0].equals("String"))
{
ArrayList<String> array = new ArrayList<String>();
sort(array, args[1], args[2]);
}
else
{
//do nothing
}
}
public static <T extends Comparable<T>> void sort(ArrayList<T> array, String input, String output)
{
try
{
File file = new File(input);
BufferedReader reader = new BufferedReader(new FileReader(file));
reader.mark((int)file.length() + 1);
int count = 0;
while(reader.readLine() != null)
{
count++;
}
reader.reset();
for(int i = 0; i<count; i++)
{
array.add((T)(reader.readLine()));
}
reader.close();
int j;
T temp;
for(int i = 1; i < array.size(); i++)
{
j = i;
while(j > 0 && array.get(j-1).compareTo(array.get(j)) > 0)
{
temp = array.get(j);
array.set(j,array.get(j-1));
array.set(j-1,temp);
j -= 1;
System.out.println(array);
}
}
PrintWriter writer = new PrintWriter(output);
for(int i = 0; i<array.size(); i++)
{
writer.write(String.valueOf(array.get(i)));
writer.write(System.getProperty ("line.separator"));
}
writer.flush();
writer.close();
}
catch(FileNotFoundException e)
{
}
catch(IOException e)
{
e.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
你有什麼證據表明'compareTo'不工作?換句話說,證明問題的最小測試用例是什麼? –
覆寫compareto? –
我很確定compareTo對於Integer,Float和String正常工作。比較負數時您期望的行爲是什麼? – nitegazer2003