英文:
Getting array out of ArrayOutOfBound exception. I was writing code to get first letters of all words in a string
问题
// 我正在编写代码,以获取字符串中所有单词的首字母。
public class Firstword {
static void func(String str) {
String k = "";
String str1 = " " + str;
char[] ch = str1.toCharArray();
for (int i = 0; i < ch.length - 2; i++) {
if (i != ch.length - 1)
while (i < ch.length && ch[i] != ' ')
i++;
k = k + ch[i + 1];
}
System.out.print(k);
System.out.print(ch.length);
}
public static void main(String[] args) {
String str = "Hello Banner jee";
func(str);
}
}
英文:
//. I was writing code to get first letters of all words in a string.
public class Firstword {
static void func(String str)
{
String k ="";
String str1=" "+str;
char[] ch= str1.toCharArray();
for(int i=0;i<ch.length-2;i++)
{
if(i != ch.length-1)
while(i<ch.length && ch[i]!=' ')
i++;
k=k+ch[i+1];
}
System.out.print(k);
System.out.print(ch.length);
}
public static void main(String[] args)
{
String str = "Hello Banner jee";
func(str);
}
}
答案1
得分: 0
Your error is here:
k = k + ch[i+1];
You are getting out of bounds.
Because of this:
while (i < ch.length && ch[i] != ' ')
i++;
Something like this will work -
static void func(String str)
{
String[] words = str.split(" ");
for (int i = 0; i < words.length; i++) {
System.out.println(words[i].charAt(0));
}
}
public static void main(String[] args)
{
String str = "Hello Banner jee";
func(str);
}
Output -
H
B
j
英文:
Your error is here:
k=k+ch[i+1];
You are getting out of bounds.
Because of this:
while(i<ch.length && ch[i]!=' ')
i++;
Something like this will work -
static void func(String str)
{
String [] words = str.split(" ");
for(int i = 0; i < words.length ;i++){
System.out.println(words[i].charAt(0));
}
}
public static void main(String[] args)
{
String str = "Hello Banner jee";
func(str);
}
Output -
H
B
j
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论