Jim Jim - 4 months ago 26
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?


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 \\