简体   繁体   English

使用 Scanner 在 Java 中读取日期

[英]Read date in Java with Scanner

Well, i'm trying to read a string with scanner in the same line.好吧,我正在尝试在同一行中使用扫描仪读取字符串。 For exapme ,i want to read: Monday 12 December 2013 and this needs to be put in a String variable so as to help me print it.例如,我想阅读:2013 年 12 月 12 日星期一,这需要放入一个字符串变量中以帮助我打印它。

In my code there is this:在我的代码中有这样的:

sale.setDate(sc.next());

with the command sc.next() i can't put a date in the form i mentioned but only in a form like: mmddyy or mm/dd/yyyy使用命令sc.next()我不能以我提到的形式输入日期,而只能以如下形式输入:mmddyy 或 mm/dd/yyyy

How can i read a whole string like "Monday 12 December 2013 " ?我怎样才能读取像“2013 年 12 月 12 日星期一”这样的整个字符串?

There is a confusion for me about sc.next sc.nextLine etc..我对 sc.next sc.nextLine 等感到困惑。

For scanner:http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html The next() and hasNext() methods first skip any input that matches the delimiter pattern, and then attempt to return the next token.对于扫描仪:http ://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html next() 和 hasNext() 方法首先跳过与分隔符模式匹配的任何输入,然后尝试返回下一个令牌。 nextLine advances this scanner past the current line and returns the input that was skipped. nextLine 将此扫描器推进到当前行并返回被跳过的输入。

Use a date DateFormat to parse string to date;使用日期 DateFormat 将字符串解析为日期; I suppose setDate expects a Date我想 setDate 需要一个日期

    Scanner scanner = new Scanner("Monday 12 December 2013,a, other fields");
    scanner.useDelimiter(",");

    String dateString = scanner.next();
    //System.out.println(dateString);

    DateFormat formatter = new SimpleDateFormat("EEEE dd MMM yyyy");
    Date date = formatter.parse(dateString);
    //System.out.println(date);
    sale.setDate(sc.next()); 

Even i faced the same issue but after that able to resolve with below mentioned code.即使我也遇到了同样的问题,但之后可以使用下面提到的代码解决。 Hope it helps.希望能帮助到你。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;

public class Datinput {

    public static void main(String args[]) {
        int n;
        ArrayList<String> al = new ArrayList<String>();
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        String da[] = new String[n];
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        sdf.setLenient(false);
        Date date[] = new Date[n];
        in.nextLine();
        for (int i = 0; i < da.length; i++) {
            da[i] = in.nextLine();
        }
        for (int i = 0; i < da.length; i++) {

            try {
                date[i] = sdf.parse(da[i]);
            } catch (ParseException e) {

                e.printStackTrace();
            }
        }

        in.close();
    }
}

Another way to do this is by utilizing LocalDateTime and DateTimeFormatter from Java 8. Found this example here :另一种方法是利用 Java 8 中的LocalDateTimeDateTimeFormatter在这里找到这个例子:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(yyyy-MM-dd HH:mm:ss.SSS);
LocalDateTime dateTime = LocalDateTime.parse(s.next(), formatter);
System.out.println(dateTime.format(formatter));

Check the link for an in-depth explanation!检查链接以获得深入的解释!

Try this..尝试这个..

public void readDate() throws Exception{
    String dateFormat = "dd/MM/yyyy";
    Scanner scanner = new Scanner(System.in);
    setDate(new SimpleDateFormat(dateFormat).parse(scanner.nextLine()));
}
public void setDate(Date date){
    // do stuff
}

chage the dateFormat as you want..根据需要更改 dateFormat ..

You have to use nextLine to fetch words with intermediate spaces.您必须使用 nextLine 来获取带有中间空格的单词。

next() can read the input only till the space. next() 只能读取输入直到空格。 It can't read two words separated by space.它无法读取由空格分隔的两个单词。 Also, next() places the cursor in the same line after reading the input.此外,next() 在读取输入后将光标置于同一行。

nextLine() reads input including space between the words (that is, it reads till the end of line \\n). nextLine() 读取输入,包括单词之间的空格(即,它读取到行尾 \\n)。 Once the input is read, nextLine() positions the cursor in the next line.读取输入后,nextLine() 将光标定位在下一行。

Scanner sc=new Scanner(System.in);
System.out.println("enter string for c");
String c=sc.next();
System.out.println("c is "+c);
System.out.println("enter string for d");
String d=sc.next();
System.out.println("d is "+d);

OUTPUT:输出:

enter string for c
abc def             
c is abc  
enter string for d
d is  defabc def| 

in the first case abc |def //cursor stays after c在第一种情况下 abc |def //光标停留在 c 之后

in the second case abc def|在第二种情况下 abc def| //cursor stays after for //光标停留在for

I found this question interesting but there is not a fully correct answer, so here is a simple solution to easily read and parse a Date form the Scanner .我发现这个问题很有趣,但没有完全正确的答案,所以这里有一个简单的解决方案,可以轻松读取和解析来自ScannerDate

The best approch would be to create a method that would do it for you, since Scanner is final, we can only do a toolbox instead of a subclass.最好的方法是创建一个方法来为你做这件事,因为Scanner是最终的,我们只能做一个工具箱而不是一个子类。 But this would be easy to use :但这很容易使用:

public static Date readDate(Scanner sc, String format){
     return new SimpleDateFormat(format).parse(sc.nextLine());
}

This would accept the format and the Scanner, don't manage it here because it would be messy to open a Scanner without closing it (but if you close it, you can't open it again).这将接受格式和扫描仪,不要在这里管理它,因为打开Scanner而不关闭它会很麻烦(但如果关闭它,则无法再次打开它)。

Scanner sc = new Scanner(System.in);
ToolBox.readDate(sc, "YYYY-MM-DD");
ToolBox.readDate(sc, "YYYY-MM-DD HH:mm:ss");
ToolBox.readDate(sc, "YYYY-MM-DD");
sc.close();

This could be improved by not recreating a SimpleDateFormat each time but a Scanner is not called that much (you are limit by the user inputs) so this is not that important.这可以通过不每次都重新创建SimpleDateFormat来改进,但是 Scanner 并没有被调用那么多(您受到用户输入的限制)所以这不是那么重要。

try this one试试这个

final Scanner sc = new Scanner(System.in);
final String timeString = sc.next();
final LocalTime time = LocalTime.parse(timeString);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM