java - 我必须在 Java 中将 String 的第一个字母大写。(我不能使用 string 类中的方法来这样做)。但我一直越界错误
问题描述
这是代码。我不断收到错误:字符串索引超出范围:5,我不知道我做错了什么,因此我们将不胜感激。此外,我不允许使用除长度以外的任何 Scanner 类方法。
import java.util.*;
public class capitalLetter
{
public static void main(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a non capitalized word");
String word = sc.next();
int length = word.length();
char ch[] = new char[length];
for(int i = 0;i<length-1;i++){
ch[length] = word.charAt(length);
}
ch[0]+=32;
for(int i = 0;i<length-1;i++){
System.out.print(ch[length]);
}
}
}
解决方案
首先,在for
循环中,您需要使用循环变量i
,而不是length
. 此外,i
应该转到数组的最后一个元素。
这个
for(int i = 0; i < length-1; i++){
ch[length] = word.charAt(length);
}
应该
for(int i = 0; i < length; i++){
ch[i] = word.charAt(i);
}
其次,当你应该减去时,你加了 32。
把它放在一起你得到:
String word = "hello";
int length = word.length();
char ch[] = new char[length];
for(int i = 0; i < length; i++) {
ch[i] = word.charAt(i);
}
ch[0] -= 32;
for(int i = 0; i < length; i++) {
System.out.print(ch[i]);
}
输出:
Hello
推荐阅读
- javascript - Angular Firestore Valuechanges 获取文档参考
- powershell - 在 AD 中查找用户所属的所有组(包括嵌套组)
- spring-boot - Oauth2 SpringBoot注销问题
- javascript - Angular 10 - NGRX 升级问题:无法添加属性 x 对象不可扩展并且无法分配给对象的只读属性 x
- macos - Macos 中的隐蔽日期模式抛出日期:不存在的时间
- python - 如果下载按钮没有 URL,如何从网站下载 CSV 文件?
- dynamic - 通过 elementor 向 wordpress RSS 提要添加动态功能
- javascript - 相同 HTML 上的 2 个 D3.js 条形图。一个 D3 脚本破坏了另一个
- json - 使用 hazelcast jet 处理 JSON
- powershell - 如何在经典devop(不是yaml)中设置变量并在不同任务之间传递?