【问题标题】:Parse text using scanner & useDelimiter / right regula expression使用扫描仪和分隔符解析文本/编写正则表达式
【发布时间】:2013-11-24 16:02:28
【问题描述】:

我想计算两个日期之间的天数,但我在解析输入流时遇到问题...

如果我输入像“22 1 2013”​​这样的日期,它会正常工作,但我很难做到:

22.1.2013

22-01-2013

2013 年 1 月 22 日

不幸的是,我对正则表达式知之甚少,我使用 useDelimiter 进行的所有测试都失败了;也许你可以帮助我(我只允许导入扫描器类):

import java.util.Scanner;

public class NewDateDifference {

public static void main(String[] args) {

    int day1, day2, month1, month2, year1, year2; 

    Scanner scan = new Scanner(System.in);

        System.out.print("First Date:\t");

        day1 = scan.nextInt(); 
    month1 = scan.nextInt(); 
    year1 = scan.nextInt();


    /**    scan = new Scanner(scan.next()).useDelimiter("\\.");
        if ( scan.hasNextInt() ) {
            day1 = scan.nextInt();
        }
        if ( scan.hasNextInt() ) {
            month1 = scan.nextInt();
        }
        if ( scan.hasNextInt() ) {
            year1 = scan.nextInt(); 
        }
        scan.close(); **/



        System.out.print("Second Date:\t");
        day2 = scan.nextInt(); 
        month2 = scan.nextInt();
        year2 = scan.nextInt(); 

        int diff = calculateDays(year2, month2, day2) - calculateDays(year1, month1, day1);
        System.out.println("Days: " + Math.abs(diff));

}

public static int calculateDays(int year, int month, int day) {

    int[] dayTillMonth = {0, 31, 61, 92, 122, 153, 184, 214, 245, 275, 306, 337};

    if(month < 3) {
        year -= 1; month += 9;
    } else {
        month -= 3;
    }
    return year * 365 + year/4 - year/100 + year/400 + dayTillMonth[month] + day;
}
  }

【问题讨论】:

    标签: java regex date java.util.scanner


    【解决方案1】:

    试试这个分隔符

    scan.useDelimiter("[\\s.\\-/]+");
    

    它将一个或多个字符设置为分隔符

    • \\s\r\n 中的空格
    • .
    • -
    • /

    【讨论】:

    • 谢谢;我可以以某种方式检查分隔符是否会使用 / 吗?因为在美国的日期是 MM/DD/YYYY,而在德国的日期是 DD MM YYYY ...
    • @user3025448 我怀疑您是否可以访问找到的分隔符,因为它是应该省略的字符。也许使用不同的方法,例如读取整行,检查位置 2 上的字符(假设第一个字符的索引为 0),然后使用 [\\s.\\-/] 分割这一行(这样您将获得像 ["DD", "MM", "YYYY"] 这样的字符串数组,然后只需将该数组的每个元素转换为整数,例如几天int day = Integer.parseInt(array[0])
    • hm 我试图用一个简单的 if 命令来修复它,但它似乎不起作用。你知道为什么吗?:String eingabe1 = scan.toString(); if (eingabe1.contains("/")) { ... }
    • @user3025448 你觉得scan.toString();应该怎么做?我怀疑你想使用scan.readLine();
    【解决方案2】:

    取消注释代码中的注释部分,并使用以下内容:

    .useDelimiter("."); //for 22.1.2013
    .useDelimiter("\\"); //for 22\1\2013
    .useDelimiter("/"); //for 22/1/2013 (most used i think)
    .useDelimiter("-"); //for 22-1-2013
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-26
      • 2014-10-31
      • 1970-01-01
      • 2011-02-25
      • 1970-01-01
      • 2020-08-03
      • 1970-01-01
      • 2014-04-03
      相关资源
      最近更新 更多