【问题标题】:Why isn't the first character uppercase?为什么第一个字符不是大写的?
【发布时间】:2015-08-06 09:20:48
【问题描述】:

我发现了应该将第一个字符从小写字母更改为大写字母的语法。

由于某种原因,我的程序不会!当我输入“m”而不是“M”时。

我在这里做错了什么?

public static void main(String[] args) {
    System.out.print("Enter two characters: ");

    Scanner input = new Scanner(System.in);
    String twoChar = input.nextLine();

    if(twoChar.length() > 2 || twoChar.length() <= 1){
        System.out.println("You must enter exactly two characters");
        System.exit(1);
    }

    char ch = Character.toUpperCase(twoChar.charAt(0));

    if(twoChar.charAt(0) == 'M'){
        if(twoChar.charAt(1) == '1'){
            System.out.println("Mathematics Freshman");
        }else if(twoChar.charAt(1) == '2'){
            System.out.println("Mathematics Sophomore");
        }else if(twoChar.charAt(1) == '3'){
            System.out.println("Mathematics Junior");
        }else if(twoChar.charAt(1) == '4'){
            System.out.println("Mathematics Senior");
        }
    }

【问题讨论】:

  • 因为您复制了大写字符,然后针对原始字符进行测试。针对副本进行测试ch

标签: java string char uppercase lowercase


【解决方案1】:

代替

if(twoChar.charAt(0) == 'M'){

使用

if(ch == 'M'){

您正在获取大写字符,但随后没有使用它。

【讨论】:

  • 谢谢,现在都修好了
【解决方案2】:

您将字符的大写版本分配给变量ch,然后您没有检查ch;您正在再次检查字符串中的字符。那个字符和以前一样:它没有改变。

所以不要检查:

if (twoChar.charAt(0) == 'M') {

检查:

if (ch == 'M') {

【讨论】:

    【解决方案3】:

    不使用局部变量

    你没有使用你在这里大写的char ch

    char ch = Character.toUpperCase(twoChar.charAt(0));
    if(twoChar.charAt(0) == 'M'){
    

    您可以通过使用 局部变量 ch 来修复它

    char ch = Character.toUpperCase(twoChar.charAt(0));
    if (ch == 'M') {
    

    或通过将toUpperCase 调用内联

    // char ch = Character.toUpperCase(twoChar.charAt(0));
    if (Character.toUpperCase(twoChar.charAt(0)) == 'M') {
    

    或使用逻辑或类似

    char ch = twoChar.charAt(0);
    if (ch == 'M' || ch == 'm') {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-06
      • 1970-01-01
      • 2011-01-26
      • 1970-01-01
      • 2019-04-03
      相关资源
      最近更新 更多