簡體   English   中英

您如何比較已轉換為整數的字符串的值(大於/小於)?

[英]How do you compare values (greater than/less than) of strings that have been turned into integers?

因此,我必須編寫一個從用戶處獲取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);

偉大的問題和夢幻般的代碼! 該解決方案非常簡單,從代碼的外觀上,您只需復制date1並粘貼到date2 但是,您並未更改所有變量,因此代碼將date1date1進行了date1 ,因此出現了錯誤。 確保將date1更改為date2並將splitStringssplitStrings2

還是針對您的代碼的一些建議,如果您只比較天數,我將再次查看相同的if語句日期。 嘗試date1=1/2/2 date2=2/2/2date2=2/2/2 ,您將看到問題!

當心第二個日期,您需要更改date1.split("/"); date2.split("/")

將您的第二個日期的前兩行替換為以下內容:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM