Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the Scanner class have a nextChar method? [closed]

Tags:

java

This is really a curiosity more than a problem...

Why doesn't the Scanner class have a nextChar() method? It seems like it should when you consider the fact that it has next, nextInt, nextLine etc method.

I realize you can simply do the following:

userChar = in.next().charAt(0); System.out.println( userChar  ); 

But why not have a nextChar() method?

like image 961
Katana24 Avatar asked Sep 11 '13 16:09

Katana24


People also ask

Is nextChar a method of Scanner class?

nextChar() scanner class in JavaThere is no classical nextChar() method in Java Scanner class. The best and most simple alternative to taking char input in Java would be the next(). charAt(0).

How do you close a Scanner in Java?

close() method closes this scanner. If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked.

How do I turn off the Scanner nextLine?

You can cancel active requests for input either by interrupting the thread, or by calling cancel(), which canceles the currently waiting request. It uses Semaphores and threads to create a blocking nextLine() method that can be interrupted/canceled elsewhere.

What is nextChar in Java?

In Java, the NextChar() and Next() operate and return consequent token/word within the input as a string and charAt() the first returns the primary character in that string.


1 Answers

The reason is that the Scanner class is designed for reading in whitespace-separated tokens. It's a convenience class that wraps an underlying input stream. Before scanner all you could do was read in single bytes, and that's a big pain if you want to read words or lines. With Scanner you pass in System.in, and it does a number of read() operations to tokenize the input for you. Reading a single character is a more basic operation. Source

You can use (char) System.in.read();.

like image 168
Frithjof Avatar answered Sep 28 '22 02:09

Frithjof