开发者

Using a forward slash as a Scanner delimiter

开发者 https://www.devze.com 2023-04-08 21:06 出处:网络
I\'m trying to use a Scanner to get a date from the user in MM/DD/YYYY f开发者_如何学Cormat and using a delimiter / to do so, but as soon as the user inputs data the application ceases to continue. It

I'm trying to use a Scanner to get a date from the user in MM/DD/YYYY f开发者_如何学Cormat and using a delimiter / to do so, but as soon as the user inputs data the application ceases to continue. 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 );
        }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消