Using delimiters, why the scanner does not return?

I am doing an exercise from an introduction to object-oriented programming with Java C. Thomas Wu.

Page 73 provides a code to request the full name, marks it with a separator, and prints it.

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 + "."); } } 

The problem is that my version does not seem to want to print it, and it freezes the program, forcing it to use the task manager to close it.

Current program

It compiles and presents no errors. Several times I checked for spelling errors, etc.

IDE with delimiter code

If I delete the separator section (last pic), it works with one first token to the first place. So the error lies somewhere around the delimiter code.

IDE without a separator code

+5
source share
1 answer

It seems that your IDE console is not considering the [Enter] line separator. The best way to try if your code works is to call the compiled Java file directly from the terminal (console in Windows). Of course, firstly, you need to go to the directory where the compiled Java file is saved (where the Scanner1.class file is located).

eg. java Scanner1

If you want to be system independent, the best way to do this is to compile the template with which you define the delimiter, or just use the built-in .nextLine () method to link to Oracle documents

 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); } } 
+5
source

Source: https://habr.com/ru/post/1236714/


All Articles