I have to use Scanner
, so is there a nextChar()
instead of nextLine()
method that I could use?
Thanks!
To take a char input using Scanner and next(), you can use these two lines of code. Scanner input = new Scanner (system.in); char a = input. next().
Reading the contents of a file − To read the contents of a file, Scanner class provides various constructors. Used to read data from the file represented by the given File object. Used to read data from the specified InputStream.
Scanner is simple text scanner which can parse primitive types and strings using regular expressions. So, passing System.in to Scanner allows us to parse or read string from standard input stream, which is console.
If you have to use a Scanner
(as you noted in your edit), try this:
myScanner.useDelimiter("(?<=.)");
Now myScanner
should read character by character.
You might want to use a BufferedReader
instead (if you can) - it has a read
method that reads a single character. For instance, this will read and print the first character of your file:
BufferedReader br = new BufferedReader(new FileReader("somefile.txt"));
System.out.println((char)br.read());
br.close();
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