Jim Jim - 1 year ago 78
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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download