【问题标题】:Converting Strings to Uppercase with charAt使用 charAt 将字符串转换为大写
【发布时间】:2016-03-29 17:53:04
【问题描述】:

我正在编写一个程序,要求用户以小写形式输入他们的姓氏,并询问他们是否希望将其输出为全部大写或仅首字母大写。我遇到的问题是将 charAt 与 toUpperCase 一起使用。

import java.util.Scanner;
//This imports the scanner class
public class ChangeCase {

    public static void main(String[] args) {
        Scanner scan = new Scanner (System.in);
        //This allows me to use the term scan to indicate when to scan
        String lastName;
        //sets the variable lastName to a string
        int Option;

    System.out.println("Please enter your last name");
    //Prints out a line
    lastName = scan.nextLine();
    //scans the next line of input and assigns it to the lastName variable
    System.out.println("Please select an option:"+'\n'+"1. Make all leters Capitalised"+'\n'+ "2. Make the First letter Capitalised");
    Option = scan.nextInt();
    if (Option == 1){
        System.out.println(lastName.toUpperCase());
    }
    if (Option == 2){
        System.out.println(lastName.charAt(0).toUpperCase());

    }
    }

}

我收到一条错误消息“无法在原始类型 char 上调用 toUpperCase()”

【问题讨论】:

  • 请编辑您的问题,并粘贴您的代码文本(不是指向您的代码图像的链接)。粘贴后,选择文本并按 ctrl-k 以缩进必要的 4 个空格。

标签: java eclipse


【解决方案1】:

您不能像您的错误所说的那样在char 上应用String.toUpperChase。如果您想让第一个字母大写,您可以执行以下操作:

    String lastName = "hill";
    String newLastName = lastName.substring(0, 1).toUpperCase() + lastName.substring(1);
    System.out.println(newLastName);

运行示例:

运行:
希尔
构建成功(总时间:0 秒)

如果你想要所有字母大写,那么简单

    newLastName = lastName.toUpperCase();
    System.out.println(newLastName);

运行示例:

运行:
希尔
构建成功(总时间:0 秒)

【讨论】:

  • 谢谢,这帮助很大。
  • @AlexRBurgess 很高兴听到这个消息!不要忘记接受。干杯!
【解决方案2】:

我曾经在大学的 C 编程中尝试过这个。也应该在这里工作。

(char)(lastName.charAt(i) - 32)

在 System.out.println 中尝试上述方法

当我们从字符中减去 32 时,它会将 ascii 值减少 32,因此得到大写字母。只需参考一个 ascii 表,通过扣除表中的 32 个位置来了解我想表达的意思。

【讨论】:

    【解决方案3】:

    正如您的错误告诉您的那样,您不能在原始 char 类型上调用 String.toUpperCase()。

    System.out.println(lastName.charAt(0).toUpperCase());
    

    但是,你可以调用Character.toUpperCase(char)like

    System.out.println(Character.toUpperCase(lastName.charAt(0)));
    

    或者,调用String.toUpperCase(),然后取第一个字符。喜欢,

    System.out.println(lastName.toUpperCase().charAt(0));
    

    【讨论】:

      猜你喜欢
      • 2018-09-16
      • 2019-07-15
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 2012-01-08
      • 1970-01-01
      • 2014-07-17
      相关资源
      最近更新 更多