将每个字符的字符串打印两次 package com.pack7; /*任务是获取一个字符串并再次打印该字符串,但这次每次 *字符打印两次。假设输入为:“java”,输出为:“jjaavvaa” */ 公共B类{ 公共字符串doubleChar(字符串str) { char[]ch=str.toCharArray();//将给定字符串转换为char数组 char[]ch2=new char[ch.length*2];//创建了另一个长度为第一个数组两倍的数组 对于(inti=0;i
这是一个愚蠢的程序。你的循环覆盖了上一次迭代 字符,因为您没有正确计算ch2索引。请尝试以下操作:将每个字符的字符串打印两次 package com.pack7; /*任务是获取一个字符串并再次打印该字符串,但这次每次 *字符打印两次。假设输入为:“java”,输出为:“jjaavvaa” */ 公共B类{ 公共字符串doubleChar(字符串str) { char[]ch=str.toCharArray();//将给定字符串转换为char数组 char[]ch2=new char[ch.length*2];//创建了另一个长度为第一个数组两倍的数组 对于(inti=0;i,java,arrays,for-loop,Java,Arrays,For Loop,这是一个愚蠢的程序。你的循环覆盖了上一次迭代 字符,因为您没有正确计算ch2索引。请尝试以下操作: package com.pack7; /* The task is to take a string and print the string again but this time every *character print twice. say input is:"java", output should be :"jjaavvaa" */ p
package com.pack7;
/* The task is to take a string and print the string again but this time every
*character print twice. say input is:"java", output should be :"jjaavvaa"
*/
public class ClassB {
public String doubleChar(String str)
{
char[] ch = str.toCharArray();//converted the given string to char array
char[] ch2 = new char[ch.length*2];//created another array of twice the length of first array
for(int i=0;i<ch.length;i++)
{
ch2[i]=ch[i];//assigning 1st char of 1st array in the 2nd array(index 0)
ch2[i+1]=ch[i];//assigning 1st char of 1st array in the 2nd array(index 0+1)
}
String result = new String(ch2);//and passing the 2nd array as parameter to create string
return result;// returning the string as answer
}
public static void main(String[] args)
{
ClassB obj = new ClassB();
String s = obj.doubleChar("java");
System.out.println(s);//but it prints "javaa", i can't figure out why my logic is not working
}
}
for(int i=0;i您正在用下一个字符(下一个i位置)覆盖您添加的第二个字符。
for(int i=0;i<ch.length;i++)
{
ch2[2*i]=ch[i];//assigning 1st char of 1st array in the 2nd array(index 0)
ch2[2*i+1]=ch[i];//assigning 1st char of 1st array in the 2nd array(index 0+1)
}