gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:45:57 25 4
gpt4 key购买 nike

我正在编写一个程序,要求用户以小写形式输入姓氏,并询问他们是否希望将其输出为全部大写或仅将第一个字母大写。我遇到的问题是将 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()”

最佳答案

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

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

运行示例:

run:
Hill
BUILD SUCCESSFUL (total time: 0 seconds)

如果您希望所有字母都大写,则很简单

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

运行示例:

run:
HILL
BUILD SUCCESSFUL (total time: 0 seconds)

关于java - 使用 charAt 将字符串转换为大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36291601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com