在java中以类似矩阵的形式打印字符数组
我正在编写一个程序来显示一个字符数组(见下文)。但是,我的代码现在的输出是这样的:在java中以类似矩阵的形式打印字符数组,java,Java,我正在编写一个程序来显示一个字符数组(见下文)。但是,我的代码现在的输出是这样的: hhhhehehehelhelhelhellhellhell 我想展示的是: h e l l o w o r l d n e w d a y 这是我目前的代码: String str = "helloworldnewday"; double length = Math.sqrt(str.length()); int x = (int) length; char[] ch
hhhhehehehelhelhelhellhellhell
我想展示的是:
h e l l
o w o r
l d n e
w d a y
这是我目前的代码:
String str = "helloworldnewday";
double length = Math.sqrt(str.length());
int x = (int) length;
char[] ch = new char[str.length()];
for (int i = 0; i < x; i++) {
for (int j = 1; j< x; j++){
ch[i] = str.charAt(i);
System.out.print(ch);
}
}
String str=“helloworldnewday”;
double-length=Math.sqrt(str.length());
int x=(int)长度;
char[]ch=新字符[str.length()];
对于(int i=0;i
我知道我的代码很糟糕,因为我刚刚开始学习。你们能告诉我我的代码有什么问题吗?我感谢你的每一个回答。谢谢。您只需要一个
就可以在字符串的所有字符上循环。使用模数运算符(%
)检查是否需要打印新行。请参阅下面的代码
当您从未调用println()
时,不清楚该代码应该如何打印多行文本。当您从未在代码中使用它时,j
的目的是什么?
String str = "helloworldnewday";
double length = Math.sqrt(str.length());
int x = (int) length;
for (int i = 0, len = str.length(); i < len; i++) {
System.out.print(str.charAt(i) + " ");
if (i % x == x - 1) {
System.out.println();
}
}
h e l l
o w o r
l d n e
w d a y