[英]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
。 但是,您并未更改所有变量,因此代码将date1
与date1
进行了date1
,因此出现了错误。 确保将date1
更改为date2
并将splitStrings
为splitStrings2
。
还是针对您的代码的一些建议,如果您只比较天数,我将再次查看相同的if语句日期。 尝试date1=1/2/2
date2=2/2/2
和date2=2/2/2
,您将看到问题!
当心第二个日期,您需要更改date1.split("/");
与date2.split("/")
将您的第二个日期的前两行替换为以下内容:
String date2 = dateInput.next();
String[] splitStrings2 = date2.split("/");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.