Cara menggunakan INPUT.NEXTCHAR pada JavaScript
Show How to add Java Scanner char supportThe Java Scanner class provides methods that take String input and convert that String into any Java primitive type you might need, except for one: the char. The Java Scanner class provides the following self-explanatory methods:
But the one
method it doesn’t have is Implement a Java Scanner nextChar methodNaturally, all Java developers, after learning the Java Scanner class has no By default, the Scanner class reads a line of input from a user and tokenizes the contents based on whitespaces found in the input.
This allows a developer to loop through input one text String at a time. But you don’t have to accept the Scanner’s defaults. The Scanner class’
Scanner input one char at a timeThe trick is to change the delimiter to nothing. Just set the delimiter to two double-quotes with nothing inside: At this point, the Scanner still returns a String, although the String contains only one character. To complete the use case, you
must convert this one-character String into a single Java char with the Java Scanner char input code exampleThe code to get Scanner input one char at a time looks like this: import java.util.Scanner;
public class NextCharScanner{
// implement a nextChar Scanner method
public static void main(String[] args) {
System.out.println("Input char data to the Java Scanner: ");
Scanner charScanner = new Scanner(System.in);
charScanner.useDelimiter("");
while (charScanner.hasNext()) {
char name = charScanner.next().charAt(0);
if (name == '\n') {
return;
}
}
}
} Notice that the code has a check for the newline character, as this will be treated as an input character if not filtered out. How to read the next char with Java’s ScannerTo summarize the process, follow these steps to read user input with the Java Scanner one char at a time:
And that’s how easy it is to create a char input Scanner method in Java.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
|