【问题标题】:Time comparision in javajava中的时间比较
【发布时间】:2019-10-28 06:57:22
【问题描述】:

我只是以 HH:MM 格式获取时间并检查它是否大于 9:30 然后计数 c 增加为 1。我只是为单个用户输入时间做了。但我需要从用户那里获得多次并比较。如果大于 9:30,则增加计数值。首先获取 n 值,然后从用户那里获取 n 时间。如何更改我的代码以获取 n 时间并进行比较?

Scanner input = new Scanner(System.in);
 String time = input.nextLine();
 System.out.println();
 int c=0;
String time2 = "9:30";
 DateFormat sdf = new SimpleDateFormat("hh:mm");
 Date d1 = sdf.parse(time);
 Date d2 = sdf.parse(time2);
 if(d1.after(d2))
 {
     c++;
}
System.out.println(c);

【问题讨论】:

  • 循环是你的朋友
  • 我建议你不要使用SimpleDateFormatDate。这些类设计不良且过时,尤其是前者,尤其是出了名的麻烦。相反,只需使用来自java.time, the modern Java date and time APILocalTime
  • 12:15 是否算作 9:30 之后?我输入了12:15,你的sn-p 打印了0。这不是你的错,而是 SimpleDateFormat 行为不端。

标签: java time user-input datetime-comparison


【解决方案1】:

应该这样做。这是一个基本的实现,您可以按照自己喜欢的方式对其进行优化。

编辑(带有解释 cmets):

Scanner sc = new Scanner(System.in);

// accept user input for N
System.out.println("Enter N");
int n = sc.nextInt();

String time;
int c = 0;

// store the DateFormat to compare the user inputs with
String time2 = "9:30";
DateFormat sdf = new SimpleDateFormat("hh:mm");
Date d2 = null;
try {
    d2 = sdf.parse(time2);
} catch (ParseException e) {
    e.printStackTrace();
}

// iterate for N times, asking for a user input N times.
for (int i = 0; i < n; i++) {
    // get user's input to parse and compare
    System.out.println("Enter Time");
    time = sc.next();
    Date d1 = null;
    try {
        d1 = sdf.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    if (d1.after(d2))  {
        c++;
    }
}
System.out.println(c);

我并没有对你的代码做太多改动,只是添加了一个循环并做了 N 次同样的事情。引用上面的 cmets 的话,“循环是你的朋友”。

希望这会有所帮助。祝你好运。如果您有任何其他问题,请发表评论。

【讨论】:

  • 它有效.....但是你为什么使用try catch?你能解释一下吗?
  • Try catch 用于采用防御性编程。如果用户输入的字符串在 DateFormat 中不可解析怎么办?此外,如果不使用 try-catch,则会出现编译时错误。
  • 如果我们使用 sc.nextLine() 它会显示异常。为什么我们不能使用它?
【解决方案2】:

使用for loop 遍历时间列表。另外,不需要n值,直接用list.size()获取即可

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

【讨论】:

  • n 值应该由用户输入。这是必需的。
  • 这更像是评论而不是答案。
  • 您不应提供直接解决方案。那不是stackoverflow的工作方式。请再次阅读指南。
猜你喜欢
  • 1970-01-01
  • 2015-09-22
  • 2011-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多