java中的星和数的平方
我必须创建一个结果如下的方法:java中的星和数的平方,java,for-loop,Java,For Loop,我必须创建一个结果如下的方法: for n = 5 * 2 3 4 5 * * 3 4 5 * * * 4 5 * * * * 5 * * * * * 我的尝试: int n = 5; for (int i = 0; i < n; i++) { String row = ""; for (int j = 0; j < n; j++) { row += "*"; if (i==j) { Sys
for n = 5
* 2 3 4 5
* * 3 4 5
* * * 4 5
* * * * 5
* * * * *
我的尝试:
int n = 5;
for (int i = 0; i < n; i++) {
String row = "";
for (int j = 0; j < n; j++) {
row += "*";
if (i==j) {
System.out.print(row + "\n");
}
}
}
}
听起来你好像在试着解决一个小测验。 你要寻找的是一个网格的模式,你的答案并不遥远 回顾您的原始样本: 当X(水平)大于Y(垂直)时,我们打印X,否则我们打印星号。每个元素之间都有一个空格
public class Main9 {
for (int i = 0; i < n; i++) {
String row = "";
for (int j = 0; j < n; j++) {
if (i > j) {
// Now we should append X (or i in this case) to the row
// Adding 1 to the base 0 integer
// and appending with a space
row += (i+1)+" ";
} else {
// Otherwise just add "* "
row += "* ";
}
}
// Now that we're done with the j-loop we can print out the row
System.out.println(row);
}
公共类main 9{
对于(int i=0;ij){
//现在我们应该将X(在本例中是i)附加到行中
//将1添加到基0整数
//并附加一个空格
行+=(i+1)+”;
}否则{
//否则只需添加“*”
行+=“*”;
}
}
//现在我们已经完成了j循环,我们可以打印出行了
系统输出打印项次(行);
}
}安娜,你应该这样做:
int n = 5;
for (int i = 0; i < n; i++) {
String row = "";
//This for build the entire output var
for (int j = 0; j < n; j++) {
if (i<j) { // if you are behind or in the line it receive a "*"
row+=String.valueOf(j+1);
} else { //if you are not it receive the number wich is j+1
row += "*";
}
}
System.out.println(row + "\n"); //Print the entire line
}
int n=5;
对于(int i=0;i 如果(i您可以不使用任何字符串连接,也不使用其他对象来执行此操作。让我提供我的解决方案:
int n = 5;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
System.out.print(j <= i ? "*" : ("" + (j + 1)));
System.out.println();
}
int n=5;
对于(int i=0;i System.out.print(j)你就像…字面上说是到了一半。如果i!=j
,你认为应该打印什么?是的,很清楚,现在我理解了这个代码:D谢谢你,它应该从星号开始,所以它是一个小小的修改int n=5;对于(int i=0;irow+=(j+1)+您好,用于“System.out.print(j)”行
int n = 5;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
System.out.print(j <= i ? "*" : ("" + (j + 1)));
System.out.println();
}