我创建了一个程序,它将温度(双精度)和日期(字符串)存储在数组列表中,然后使用可比较的接口和插入排序对数组列表进行排序。现在我剩下的就是调用插入排序方法并打印出数组列表的原始顺序和排序顺序。但是,当我调用 insertsort 方法时,它会给我一个错误,指出“方法声明无效;需要返回类型”。为什么我会收到此错误?我的打印语句也可以正确打印出原始数组列表吗?我将如何更新它以打印出排序的数组列表?或者我可以从 insertsort 方法中打印出来吗?
这是我的代码:
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
public class DailyTemperature implements Comparable<DailyTemperature>
{
//variables
private Double temperature;
private String day;
//getTemp & setTemp methods
public double getTemp()
{
return temperature;
}
public void setTemp(double newTemp)
{
temperature = newTemp;
}
//getDay & setTEmp methods
public String getDay()
{
return day;
}
public void setDay(String newDay)
{
day = newDay;
}
public DailyTemperature(String day, double temperature)
{
this.day = day;
this.temperature = temperature;
}
public int compareTo(DailyTemperature other)
{
if (temperature < other.temperature) return -1;
if (temperature == other.temperature) return 0;
return 1;
}
public String toString()
{
return("Day of Week" + this.getDay() +
"Temperature" + this.getTemp());
}
}
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class DailyTemperatureList
{
public static void main (String [] args)
{
ArrayList<DailyTemperature> dailytemps = new ArrayList<DailyTemperature>();
dailytemps.add(new DailyTemperature("Mon", 87.1));
dailytemps.add(new DailyTemperature("Tue", 88.3));
dailytemps.add(new DailyTemperature("Wed", 81.2));
dailytemps.add(new DailyTemperature("Thu", 84.0));
dailytemps.add(new DailyTemperature("Fri", 76.3));
}
public static <DailyTemperature extends Comparable<? super DailyTemperature>>
void insertionSort(ArrayList<DailyTemperature> dailytemps)
{
DailyTemperature temp = null;
int position = 0;
//loop from 2nd element on
for (int i = 1; i < dailytemps.size(); i++)
{
temp = dailytemps.get(i);
position = i;
while ( 0 < position && temp.compareTo(dailytemps.get(position - 1 )) < 0)
{
dailytemps.set(position, dailytemps.get(position - 1));
position--;
}
dailytemps.set(position,temp);
}
}
insertionSort(ArrayList<DailyTemperature> dailytemps);
System.out.println( dailytemps.toString() );
}