I’m trying to have that if a single Character is entered(Ex: ‘a’, ‘b’) it returns and displays True, but if multiple are entered it returns and displays false(Ex: ‘adf’, ‘a f e s’).
import java.util.*;
public class FinalExamTakeHome8 {
public static void main(String[] args) {
try (Scanner kbd = new Scanner(System.in)) {
System.out.println("Enter an item");
if (kbd.hasNextInt() || kbd.hasNextChar() || kbd.hasNextDouble()) {
System.out.println("True");
}
else {
System.out.println("False");
}
}
}
}
>Solution :
You could use the nextLine() method to read the user input, regardless of being one or more characters. Then, once you’ve acquired the text, check whether its length is equals to 1 or not.
public static void main(String[] args) {
try (Scanner kbd = new Scanner(System.in)) {
System.out.println("Enter an item");
String input = kbd.nextLine();
if (input.length() == 1) {
System.out.println("True");
} else {
System.out.println("False");
}
}
}
EDIT: For some reason, it does not incorporate the link properly in the text. I’ll leave the link to the Scanner documentation here:
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()