Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delimiter usage, why does Scanner not return?

Tags:

java

delimiter

I am doing an exercise from an introduction to Object Oriented Programming with Java C. Thomas Wu.

Page 73 provides the code to request the full name, tokenize it using delimiter and print it back.

import java.util.*;

class Scanner1
{
    public static void main(String[] args)
    {
        String name;
        Scanner scanner = new Scanner(System.in);

        scanner.useDelimiter(System.getProperty("line.separator"));
        System.out.print("Enter full name (first, middle, last)");   

        name = scanner.next( );
        System.out.println("you entered " + name + ".");
    }
}

Problem is, mine doesnt seem to want to print it back, and it freezes the program, forcing the use of task manager to close it.

Running Program

It compiles and presents no errors. I've been over it a few times to check for spelling errors etc.

IDE with Delimiter Code

If I remove the delimiter section (last pic) it works one first token up to first space. So the error lies somewhere around the delimiter code.

IDE without Delimiter Code

like image 934
Kyle Harris Avatar asked Nov 24 '15 14:11

Kyle Harris


1 Answers

It seems as your IDE's console is not considering [Enter] a line separator. The best way to try if your code works is to call the compiled Java file directly from the terminal(console on Windows). Of course firstly you need to navigate to the directory where the compiled Java file persists (where the Scanner1.class file is situated).

E.g. java Scanner1

If you want to be System independent, the best way to do it is to compile a Pattern by which you define the delimiter or just use the built in method .nextLine() reference to Oracle docs

public class Main {
    //These constant fields are from .nextLine() method in the Scanner class
    private static final String LINE_SEPARATOR_PATTERN ="\r\n|[\n\r\u2028\u2029\u0085]";

    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        scanner.useDelimiter(Pattern.compile(LINE_SEPARATOR_PATTERN));
        System.out.print("Enter name:");
        String name = scanner.next();
        System.out.println(name);
    }
}
like image 66
Bogomil Dimitrov Avatar answered Sep 30 '22 14:09

Bogomil Dimitrov