Java:如何编写一个使用 boolean 值和字符串仅识别大写字母的程序

标签 java

我是编程和 Java 新手。我遇到的问题是让我的程序仅识别大写字母并在用户输入是非字母字符时显示错误消息。我被指示使用 boolean 值和字符串来解决这个问题。 谢谢!

Scanner in = new Scanner(System.in);
System.out.println("Enter a single letter, and I will tell you what the corresponding digit is on the telephone:");
String letter = in.nextLine();
String upperCase = letter.toUpperCase();
boolean letter = letter.hasUpperCase();


if (letter.equals("A") || letter.equals("B") || letter.equals("C")){
 System.out.println("The digit 2 corresponds to the letter " + letter + " on the telephone.");
}
else if{
  System.out.println("Please enter a letter.")
}

最佳答案

如果您只想检查大写字母,那么一种方法是检查每个字符的 ASCII 值,看看它是否在 65 到 90 之间的范围内。如果字符串中的所有字符都满足此条件,那么您就有一个字符串仅包含 A-Z。如果没有,您可以根据需要显示错误消息。请根据您的代码查看下面的示例。

    Scanner in = new Scanner(System.in);
    System.out.println("Your message here");
    String userInput = in.nextLine();
    in.close();
    // Here you don't know what they entered
    // but looking at your code, you want 
    // only ONE uppercase character

    // validate the input
    boolean validInput = false;

    if (userInput.length() == 1) {
        char letter = userInput.charAt(0);
        if (letter >= 65 && letter <= 90) {
            validInput = true;
        }
    }

    // handle accordingly
    if (validInput) {
        // your logic here
    } else {
        System.out.println("Your error message");
    }

编辑——如何检查字符是数字还是符号

...

    // Here you don't know what they entered

    // the validation / execution changes based on your needs
    // suggestion: define other methods

    if (userInput.length() == 1) {
        char c = userInput.charAt(0);

        // what kind of character is it?
        if (isUppercaseLetter(c)) {
            // do something with the uppercase letter
        } else if (isDigit(c)) {
            // do something with the digit
        } else if (isSymbol(c)) {
            // do something with the symbol
        } else {
            // whatever else it might be, this could be an error message
        }
    }

...

// methods here
private boolean isUppercaseLetter(char c) {
    return (c >= 'A' && c <= 'Z'); // ascii codes 65 to 90
}

private boolean isDigit(char c) {
    return (c >= '0' && c <= '9'); // ascii codes 30 to 39
}

private boolean isSymbol(char c) {
    return (c >= '!' && c <= '/'); // 21 to 47, modify based on acceptable symbols
}

关于Java:如何编写一个使用 boolean 值和字符串仅识别大写字母的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48570633/

相关文章:

java - 请求异常索引 1,大小为 1

java - context.getExternalFilesDir(null) 为空

java - jsp 中的警告 : The tag handler class for "s:form" (org. apache.struts2.views.jsp.ui.FormTag) 在 Java 构建路径上找不到

java - 逐行写入文件

java - 导航到上一个 Activity

java - I/O 概念刷新与同步

java - 我的 JavaFX 项目停止在 EventHandler 上运行代码

java - URL 和用户的 Spring Security 配置

java - PMD 自定义 junit 方法命名规则不起作用

java - Spring 启动 jackson : How to remove nulls from java array?