Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Data {
- int giorno, mese, anno;
- /**
- * Crea nuovo oggetto data, eseguendo alcuni controlli sulla correttezza
- * dell'input.
- * @param giorno
- * @param mese
- * @param anno
- */
- public Data(int giorno, int mese, int anno) {
- if (0 > giorno || anno < 0 || 0 > mese) {
- System.err.println("Non sono ammessi valori negativi");
- System.exit(1);
- }
- switch (mese) {
- case 1:
- case 3:
- case 5:
- case 7:
- case 8:
- case 10:
- case 12:{
- if (giorno > 31) {
- System.err.println("Questo mese ha 31 giorni");
- System.exit(1);
- }
- break;
- }
- case 4:
- case 6:
- case 9:
- case 11: {
- if (giorno > 30) {
- System.err.println("Questo mese ha 30 giorni");
- System.exit(1);
- }
- break;
- }
- case 2: {
- if ((anno % 4 == 0 && anno % 100 != 0) || anno % 400 == 0) {
- if (giorno > 29) {
- System.err.println("Febbraio non può avere più di 29 giorni");
- System.exit(1);
- }
- } else {
- if (giorno > 28) {
- System.err.println("Febbraio non può avere più di 28 giorni");
- System.exit(1);
- }
- }
- break;
- }
- default: {
- System.err.println("I mesi sono 12 (da 1 a 12)");
- System.exit(1);
- }
- }
- this.giorno = giorno;
- this.mese = mese;
- this.anno = anno;
- }
- /**
- * Confronta this con una data in ingresso d e restituisce un numero negativo
- * se this è precedente a d, positivo se this è successiva a d e 0 se sono
- * uguali
- * @param d Data in ingresso
- * @return <ul> <li> intero < di 0 se this è precedente a d </li>
- * <li>intero > di 0 se this è successivo a d </li>
- * <li>0 se le due date sono uguali</li></ul>
- */
- public int compareTo(Data d) {
- int compare = this.anno-d.anno;
- if (compare != 0) {
- return compare;
- }
- compare = this.mese - d.mese;
- if (compare != 0) {
- return compare;
- }
- return this.giorno - d.giorno;
- }
- public static void main(String args[]) {
- Data d1, d2;
- //input giorno, mese, anno e inizializzazione d1 e d2 (es. d1 = new Data(giorno, mese, anno) )
- int risComparazione = d1.compareTo(d2);
- if(risComparazione < 0) System.out.println("d1 è precedente a d2");
- else{
- if(risComparazione > 0) System.out.println("d1 è successivo a d2");
- else System.out.println("Le due date sono uguali");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement