gpt4 book ai didi

java - 你如何在 Java 中从大写变成小写,我的代码输出有问题

转载 作者:行者123 更新时间:2023-11-29 04:58:55 27 4
gpt4 key购买 nike

在这个 starwars 名称生成器代码中,我得到的输出是:

May the force be with you, PatSm BaSan

什么时候应该:

May the force be with you, Patsm Basan.

这是我的代码供引用。

import java.util.Locale;
import java.util.Scanner;

public class Assignment2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.printf("Enter your first name: ");
String firstname = input.nextLine().substring(0,3);
firstname = firstname.substring(0,1).toUpperCase() + firstname.substring(1).toLowerCase();

System.out.printf("Enter your last name: ");
String lastname = input.nextLine().substring(0,2);
lastname = lastname.substring(0,1).toUpperCase() + lastname.substring(1).toLowerCase();

System.out.printf("Enter your mother's maiden name: ");
String mothersname = input.nextLine();
mothersname = mothersname.substring(0,2);

System.out.printf("Enter the name of the city in which you were born: ");
String cityname = input.nextLine();
cityname = cityname.substring(0,3);

String StarWarsName = firstname+lastname+" "+mothersname+cityname;
System.out.println("May the force be with you, " + StarWarsName );
}
}

最佳答案

通过在姓氏的第一个字母上使用 toUpperCase() 使姓氏以大写字母开头。

您可以轻松修复变量 StarWarsName 的大小写。尝试:

String correctName = "";
for (int i = 0; i < starWarsName.length(); i++) {
if (i == 0 || starWarsName.charAt(i - 1) == ' ')
correctName += starWarsName.substring(i, i + 1).toUpperCase();
else
correctName += starWarsName.substring(i, i + 1).toLowerCase();
}

此外,变量名应该以小写字母开头。 ;)

关于java - 你如何在 Java 中从大写变成小写,我的代码输出有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32769143/

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