如何获取扫描仪输入以将空白注册为值

时间:2018-09-25 20:40:39

标签: java

我正在写一个代表老式电话键盘的代码。一切工作正常,除了当我尝试从用户那里获取应该打印出数字0的空格时。我也尝试过使用'\ u0020'进行Unicode,但这也不起作用。在输出中如果键入一个空格并按Enter键,则会得到另一行,因此扫描仪无法将空白识别为字符,这是我的猜测。有人,请帮忙谢谢!

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();
  }
}   

3 个答案:

答案 0 :(得分:1)

使用:

char userInput = input.nextLine().charAt(0);

代替:

char userInput = input.next().charAt(0);

答案 1 :(得分:0)

使用Scanner.nextLine()代替next():

char userInput = input.nextLine().charAt(0);

答案 2 :(得分:0)

scanner.nextLine()将捕获行中的所有内容,包括空格。

scanner.next()将不会捕获空格,因为默认情况下分隔符为空格。

因此,请尝试使用scanner.nextLine();