首页 > 解决方案 > 我必须在 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]);
           }
       }
   }

标签: javaarrays

解决方案


首先,在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

推荐阅读