3 回答

TA貢獻1812條經驗 獲得超5個贊
這個答案需要您的確切代碼,并通過一些更改到達您期望的輸出。你很接近,你只需要在每一行上打印一個間隔,并從你的第二個外環上剪下一次迭代,for以避免打印*兩次。
for (int i=1;i <= 3; i++) {
for (int k=3; k >= i; k--) {
// print a new spacer at the start of each line
if (k == 3) System.out.print(" ");
System.out.print(" " + "*" + " ");
}
for (int j=1; j <= i; j++) {
System.out.print(" ");
}
System.out.println();
}
// start at k=2 so as to NOT print a double single asterisk *
for (int k=2; k <= 3; k++) {
for (int l=0; l < k; l++) {
// print a new spacer at the start of each line
if (l == 0) System.out.print(" ");
System.out.print(" "+"*"+" ");
}
System.out.println();
}
* * *
* *
*
* *
* * *

TA貢獻1828條經驗 獲得超3個贊
首先,用其余的變量初始化 k。
int i, j, k;
然后你應該決定哪個 for 循環將負責打印的單個 '*' 并相應地調整另一個。例如,如果您提前終止第一個循環 1 步,它應該修復 2 個部分之間的間隙。
現在我保留第一個 for 循環的單個 '*' 并通過修改步驟在第二個循環中跳過它。
初始化 k=2 而不是 k=0。修復單個 * 重復以及它們之間的空間。
完全刪除了使用 j 作為計數器的 for 循環,因為它會干擾輸出中的間距,打印出不需要的 * 更遠的地方。
最后System.out.println()在第二個 for 循環之前添加了一個,以便第二個 for 循環打印的 * 將從新行開始。
import java.util.*;
import java.lang.*;
class Rextester
{
public static void main(String args[])
{
for (int i=1;i <= 3; i++) {
System.out.println();
for (int k=3; k >= i; k--) {
System.out.print(" " + "*" + " ");
}
}
System.out.println();
for (int k=2; k <= 3; k++) {
for (int l=0; l < k; l++) {
System.out.print(" "+"*"+" ");
}
System.out.println();
}
}
}
最終,這是一個通過修改數字或在編寫代碼之前解決紙筆問題來解決的問題。

TA貢獻1847條經驗 獲得超11個贊
快速而骯臟的解決方案
public static void main(String[] args) {
upperHalf(4);
bottomHalf(4);
}
private static void upperHalf(int size) {
for(int row = 0; row<size; row++){
String rowContent = "";
for(int col=0; col<size-row; col++){
rowContent+= " *";
}
if(!rowContent.equals(""))
System.out.println(rowContent);
}
}
private static void bottomHalf(int size) {
for(int row=2; row<=size; row++) {
String rowContent = "";
for(int col=0; col<row;col++)
{
rowContent+= " *";
}
System.out.println(rowContent);
}
}
添加回答
舉報