如何比較數字字符串?Java - 比較數字字符串
我保存在文件中的字符串:
"2000 12 7 0 2 -3.0"
"2000 7 7 0 2 -4.0"
"2013 7 23 20 59 25.5"
首先5個值是日期(年,月,日,小時,分鐘)。我需要按照時間順序排列。
這裏是我的代碼:
class Task3 {
BufferedWriter writer;
BufferedReader reader;
int licznik = 0;
Task3() throws IOException {
this.writer = new BufferedWriter(new FileWriter("c:\\zadanie.txt"));
this.reader = new BufferedReader(new FileReader("c:\\zadanie.txt"));
}
public void WriteMeasur(Measur measur) throws IOException{
//licznik++;
writer.write(measur.toString());
writer.newLine();
}
public void WriteChrono(Measur measur) throws IOException{
List<String> lista = new ArrayList<>();
String line;
while((line = reader.readLine()) != null){
lista.add(line);
}
}
}
class Time implements Serializable{
int year, month, day, hour, minute;
Time(int r, int m, int d, int h, int min){
if(r <= 2014 && r > 1990)
this.year = r;
if(m <= 12)
this.month = m;
if(d <= 30 || (m == 2 && d < 29))
this.day = d;
if(h <= 24)
this.hour = h;
if(min <= 60)
this.minute = min;
}
@Override
public String toString(){
return String.valueOf(year) + " " + String.valueOf(month) + " " +String.valueOf(day) + " " +String.valueOf(hour) + " " +String.valueOf(minute);
}
}
class Measur implements Serializable{
Time time;
double temp;
Measur(Time czas, double temp){
this.time = czas;
this.temp = temp;
}
@Override
public String toString(){
return time.toString() + " " +String.valueOf(temp);
}
}
public class Main{
public static void main(String args[]) throws IOException{
//Argumenty klasy czas: rok, miesiac, dzien, godzina, minuty
// Metody inicjujace klase czas
Time czas_1 = new Time(2013,7,23,20,59);
Time czas_3 = new Time(2000,07,7,25,2);
Time czas_2 = new Time(2000,12,7,25,2);
// Metody inicjujace klase pomiar
Measur pomiar_1 = new Measur(czas_1, 25.5);
Measur pomiar_2 = new Measur(czas_2, -3);
Measur pomiar_3 = new Measur(czas_3, -4);
Task3 zad3 = new Task3();
zad3.WriteMeasur(pomiar_1);
zad3.WriteMeasur(pomiar_2);
zad3.WriteMeasur(pomiar_3);
zad3.writer.close();
}
}
我不知道如何對它進行排序。我想用Collections.sort()
,但在絃樂2000 12越小則7. 2000年
有什麼建議?
謝謝!
你必須看看SimpleDateFormat的 - http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html – Leo
你應該實現[比較](HTTP://文檔。 oracle.com/javase/7/docs/api/java/util/Comparator.html),或許還有一個[GregorianCalendar的](http://docs.oracle.com/javase/7/docs/api/java/util/ GregorianCalendar.html#的GregorianCalendar%28int,%20int,%20int,%20int,%20int%29)。 –