[英]Using a forward slash as a Scanner delimiter
I'm trying to use a Scanner
to get a date from the user in MM/DD/YYYY
format and using a delimiter /
to do so, but as soon as the user inputs data the application ceases to continue. 我正在尝试使用Scanner
以MM/DD/YYYY
格式从用户获取日期并使用分隔符/
来执行此操作,但是一旦用户输入数据,应用程序就会停止继续。 It will work how ever if I simply use the standard space delimiter. 如果我只使用标准空间分隔符,它将工作。
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("/");
System.out.print("Birth Date (MM/DD/YYYY) ");
birthMonth = scanner.nextInt();
birthDay = scanner.nextInt();
birthYear = scanner.nextInt();
Your only delimiter is /
not newline. 您唯一的分隔符是/
不是换行符。 This means you have to type /
after the year or add newline as a delimiter. 这意味着您必须在年份后键入/
或添加换行符作为分隔符。
Try 尝试
scanner.useDelimiter("[/\n]");
You have to accept slash and new line characters or the prompt will not return the control to the user. 您必须接受斜杠和换行符,否则提示将不会将控件返回给用户。
import java.util.Scanner;
public class Test {
public static void main( String[] args ) {
Scanner scanner = new Scanner( System.in );
scanner.useDelimiter( "[/\n]" );
System.out.print( "Birth Date (MM/DD/YYYY) " );
int birthMonth = scanner.nextInt();
int birthDay = scanner.nextInt();
int birthYear = scanner.nextInt();
scanner.close();
System.out.printf( "Day(%02d), Month(%02d), Year(%04d)%n", birthDay, birthMonth, birthYear );
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.