Java 使用charAt将字符串转换为大写

Java 使用charAt将字符串转换为大写,java,eclipse,Java,Eclipse,我正在编写一个程序,要求用户以小写形式输入他们的姓氏,并询问他们是否希望将其输出为全部大写字母,还是仅将第一个字母大写。我遇到的问题是在toUpperCase中使用charAt import java.util.Scanner; //This imports the scanner class public class ChangeCase { public static void main(String[] args) { Scanner scan = new Sca

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

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()”

您不能像错误所说的那样在
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秒)


您不能像错误所说的那样,在
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秒)


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

(char)(lastName.charAt(i) - 32)
在System.out.println中尝试上述方法


当我们从字符中减去32时,代码将ascii值减少32,因此得到大写字母。只要参考一个ascii表格,通过在表格中扣除32个位置来理解我想说的内容

我在大学时曾在C编程中尝试过这一点。应该也在这里工作

(char)(lastName.charAt(i) - 32)
在System.out.println中尝试上述方法


当我们从字符中减去32时,代码将ascii值减少32,因此得到大写字母。只要参考一个ascii表格,通过在表格中扣除32个位置来理解我想说的内容

正如错误告诉您的那样,您不能对原语
char
类型进行调用

System.out.println(lastName.charAt(0).toUpperCase());
但是,您可以调用

,调用
String.toUpperCase()
,然后获取第一个字符。像

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

正如错误告诉您的那样,您不能对基元
char
类型进行调用

System.out.println(lastName.charAt(0).toUpperCase());
但是,您可以调用

,调用
String.toUpperCase()
,然后获取第一个字符。像

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

请编辑您的问题,并将代码文本粘贴到中(而不是代码图像的链接)。粘贴后,选择文本并按ctrl-k将其缩进必要的4个空格。请编辑您的问题,然后将代码文本粘贴到中(而不是代码图像的链接)。粘贴后,选择文本并按ctrl-k键,使其缩进必要的4个空格。谢谢,这非常有帮助。@Alexrburges很高兴听到这个消息!别忘了接受。干杯谢谢,这帮了大忙。@Alexrburges很高兴听到这个消息!别忘了接受。干杯