我正在编写代表老式电话键盘的代码。一切都工作正常,除了当我尝试从用户那里打出数字0的空白区域时。我也尝试使用'\ u0020'的Unicode,但这也没有用。在输出中如果我键入一个空格并点击回车,我得到另一行,所以扫描仪没有将空格识别为我猜的字符。有人,请帮忙谢谢!
import java.util.Scanner;
public class phoneKeypad{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Please enter a letter: ");
char userInput = input.next().charAt(0);
if (userInput == 'a' || userInput == 'b' || userInput == 'c' ||
userInput == 'A' || userInput == 'B' || userInput == 'C')
{
System.out.println(userInput + " is the number 2!");
}
else if (userInput == 'd' || userInput == 'e' || userInput == 'f' ||
userInput == 'D' || userInput == 'E' || userInput == 'F')
{
System.out.println(userInput + " is the number 3!");
}
else if (userInput == 'g' || userInput == 'h' || userInput == 'i' ||
userInput == 'G' || userInput == 'H' || userInput == 'I')
{
System.out.println(userInput + " is the number 4!");
}
else if (userInput == 'j' || userInput == 'k' || userInput == 'l' ||
userInput == 'J' || userInput == 'K' || userInput == 'L')
{
System.out.println(userInput + " is the number 5!");
}
else if (userInput == 'm' || userInput == 'n' || userInput == 'o' ||
userInput == 'M' || userInput == 'N' || userInput == 'O')
{
System.out.println(userInput + " is the number 6!");
}
else if (userInput == 'p' || userInput == 'q' || userInput == 'r' || userInput == 's' ||
userInput == 'P' || userInput == 'Q' || userInput == 'R' || userInput == 'S')
{
System.out.println(userInput + " is the number 7!");
}
else if (userInput == 't' || userInput == 'u' || userInput == 'v' ||
userInput == 'T' || userInput == 'U' || userInput == 'V')
{
System.out.println(userInput + " is the number 8!");
}
else if (userInput == 'w' || userInput == 'x' || userInput == 'y' || userInput == 'z' ||
userInput == 'W' || userInput == 'X' || userInput == 'Y' || userInput == 'Z')
{
System.out.println(userInput + " is the number 9!");
}
else if (userInput == '\u0020')
{
System.out.println("Blank space is the number 0!");
}
else
{
System.out.println(userInput + " could be either a 1 or the character does not exist");
}
input.close();
}
}
使用:
char userInput = input.nextLine().charAt(0);
代替:
char userInput = input.next().charAt(0);
使用Scanner.nextLine()而不是next():
char userInput = input.nextLine().charAt(0);
scanner.nextLine()
将捕获该行中的所有内容,包括空格。
scanner.next()
不会捕获空格,因为默认情况下分隔符是空格。
所以,尝试使用scanner.nextLine();