Jim Jim - 1 month ago 8
Java Question

Looking for a specific character with hasNext() Java

I need to find whether the next item that a scanner will see will be character '*'.

Is there a way to use something like Scanner.hasNext('*') to find out if the next item is indeed a star?

Answer

The Scanner supports Pattern so you can use regex to your advantage and check if the next item is indeed * like this:

    Scanner scanner = new Scanner(System.in);
    boolean hasNextStar = scanner.hasNext(Pattern.compile("\\*"));

Since * is a special token in regex you have to escape it with \\

Comments