2015-10-18 61 views
0

因此,我必須編寫一個代碼,用於從用戶獲取2個日期(月/日/年),並且如果FIRST日期小於第二個日期,則返回「true」。在任何其他情況下,日期將是「假」或「他們是相同的」。我被告知我不能要求用戶使用指定的格式(即mm/dd/yyyy),而應該關注「/」。如何比較已變成整數的字符串的值(大於/小於)?

問題是,無論我放什麼東西,它總是返回「它們是相同的」答案。任何提示和建議都非常感謝!我只是一名初學者程序員,所以我不確定有什麼問題。

下面的代碼:

import java.util.Scanner; 

public class Mari_WS15IsDateEarlier { 

public static void main (String[] args) { 

//initial variables, asks for variable input and determines month/day/year 

    Scanner dateInput = new Scanner(System.in); 
    String answr; 

//splits string input into month, day and year 
System.out.println("Enter a month, day, and year(separate with a slash) :"); 
    String date1 = dateInput.next(); 
    String[] splitStrings = date1.split("/"); 
    String month1 = splitStrings[0]; 
    String day1 = splitStrings[1]; 
    String year1 = splitStrings[2]; 

System.out.println("Enter another month, day, and year (separate with a slash) :"); 
    String date2 = dateInput.next(); 
    String[] splitStrings2 = date1.split("/"); 
    String month2 = splitStrings[0]; 
    String day2 = splitStrings[1]; 
    String year2 = splitStrings[2]; 

//turns string into integer for testing (greater than/less than) 
int mn1 = Integer.parseInt(month1); 
int mn2 = Integer.parseInt(month2); 
int dy1 = Integer.parseInt(day1); 
int dy2 = Integer.parseInt(day2); 
int yr1 = Integer.parseInt(year1); 
int yr2 = Integer.parseInt(year2); 

//Determine if the set of variables is a geometric sequence 
if (yr1 < yr2) { 
    answr = "true"; 
} 
else if ((yr1 == yr2)&&(mn1 < mn2)) { 
    answr = "true"; 
} 
else if ((mn1 == mn2)&&(dy1 < dy2)) { 
    answr = "true"; 
} 
else if (dy1 == dy2) { 
    answr = "ERROR: Dates are identical."; 
} 
else { 
    answr = "false"; 
} 

//Prints out the answer 
System.out.println(answr); 
+1

這是棘手的,如果你不能強加一些* *對用戶的格式限制,否則你怎麼知道「10/03/2015」是3月10日還是10月3日? – nnnnnn

+0

您是否嘗試在每個「if-else」之前和之內打印您嘗試比較的整數值? – ahmed

+0

啊,抱歉不清楚。我們將用預期的代碼進行編碼,用戶將首先輸入月份,然後是一天,然後是一年,用斜線分隔。 我們不允許做的是要求他們做一個指定的數字格式(例如在一位數月前/日之前放一個零,他們可以放入2011年3月3日和2011年3月3日)。 – Mari

回答

1

重大課題和夢幻般的代碼!該解決方案非常簡單,從代碼的外觀您只需複製date1並粘貼爲date2。但是,您並未更改所有變量,因此代碼將date1date1進行比較,因此是您的錯誤。確保將date1更改爲date2splitStringssplitStrings2

也只是針對你的代碼的一點小建議,我會再次看看相同的日期,如果陳述,因爲你只是比較幾天。嘗試date1=1/2/2date2=2/2/2,你會看到這個問題!

+0

謝謝你這樣詳細的答案!我發現了自己的錯誤,之後它就很完美了,再加上我的代碼提示,幫助我解決了我沒有注意到的if語句的問題。 – Mari

0

觀看了適用於第2日起,您需要更改date1.split("/");date2.split("/")

與以下替換您的第二日起最上面兩行:

String date2 = dateInput.next(); 
String[] splitStrings2 = date2.split("/"); 
+1

感謝您的解決!我能夠找出這個問題(: 昨天我開始恐慌,因爲我想也許當字符串變成整數不保留它們的正確值哈哈 – Mari

相關問題