New to programming, so my apologies if this is dumb question.
When utilizing the Scanner class, I fail to see if there is an option for obtaining a single character as input. For example,
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String a = input.nextLine();
}
}
The above code allows me to pull the next line into a string, which can then be validated by using a while or if statement using a.length() != 1 and then stored into a character if needed.
But is there a way to pull a single character instead of utilizing a string and then validating? If not, can someone explain why this is not allowed? I think it may be due to classes or objects vs primitive types, but am unsure.
CodePudding user response:
You can use System.in.read()
instead of Scanner
char input = (char) System.in.read();
You can also use Scanner
, doing something like:
Scanner scanner = new Scanner(System.in);
char input = scanner.next().charAt(0);
For using String
instead of char, I prefer to convert to String
, since using regex, like the one used in the answer that specifies a delimiter, can make the code less readable:
Scanner scanner = new Scanner(System.in);
String input = String.valueOf(input.next().charAt(0));
This is less fancy than:
new Scanner(System.in).useDelimiter("(?<=.)");
But I guess that for a newbie, it'll be easier to understand any of my proposals.
CodePudding user response:
Set the delimiter so every character is a token:
Scanner input = new Scanner(System.in).useDelimiter("(?<=.)");
String c = input.next(); // one char
The regex (?<=.)
is a look behind, which has zero width, that matches after every character.