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.
It compiles and presents no errors. I've been over it a few times to check for spelling errors etc.
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With