[英]Can't figure out For Loop
我最近開始使用java,所以不幸的是我很糟糕。 我有一個關於我今天在課堂上提出的for循環問題的問題,但我無法弄清楚它的一部分。 我們應該打印出來:
__1__
_333_
55555
僅用於循環。
我已經啟動了代碼,但無法弄清楚如何打印數字,雖然我想出了空格。
public class Question{
public static void main(String [] args){
for(int j=1; j<=3;j++){
for(int i=1; i<=3-j; i++){
System.out.print(" ");
}
for(int k=?; k<=?; k??){
System.out.print(???);
}
for(int m=1; m<=3-j; m++){
System.out.print(" ");
}
System.out.println();
}
問號是我不知道那里發生了什么的地方。 謝謝。
你可以這樣做,
class Main {
public static void main(String[] args) {
int i, j, k;
for (i = 1; i <= 3; i++) {
for (j = 2; j >= i; j--) {
System.out.print("_");
}
for (k = 1; k <= (2 * i - 1); k++) {
System.out.print(i * 2 - 1);
}
for (j = 2; j >= i; j--) {
System.out.print("_");
}
System.out.println();
}
}
}
第一個for循環將在數字前打印_
,第二個將打印數字,第三個將在數字后打印_
每次j
遞增時,值都會變為2,這將導致公式1 + (2 * (j - 1))
,這就是完成循環的方法。 喜歡,
for (int j = 1; j <= 3; j++) {
for (int i = 1; i <= 3 - j; i++) {
System.out.print(" ");
}
int n = 1 + (2 * (j - 1));
for (int k = 1; k <= n; k++) {
System.out.print(n);
}
for (int m = 1; m <= 3 - j; m++) {
System.out.print(" ");
}
System.out.println();
}
輸出
1
333
55555
謝謝大家的幫助。 我想出了答案。
public class Welcome {
public static void main(String [] args){
for(int j=1; j<=3;j++){
for(int i=1; i<=3-j; i++){
System.out.print(" ");
}
for(int k=1; k<=(2*j-1); k++){
System.out.print(2*j-1);
}
for(int m=1; m<=3-j; m++){
System.out.print(" ");
}
System.out.println();
}
}
}
這也可以如下實現
public class ForLoopPrinter {
public static void main(String[] args) {
int number = 1;
int row = 3;
int column = 5;
char space = '_';
for(int i = 1; i <= row; i++){
for(int j = 1; j <=column;j++){
int offset = (column - number)/2;
if( j <= offset ||
j > (number + offset)){
System.out.print(space);
}else{
System.out.print(number);
}
}
System.out.println();
number += 2;
}
}
}
這里For循環的數量限制為2(一個用於行,一個用於列)。
邏輯是這樣的 -
我知道這個問題得到了正確答案,它會像魅力一樣起作用。 我只是嘗試通過減少之前提供的答案中的For Loops數量來優化代碼。 減少For循環將提高性能。
除了減少For循環之外,此代碼還具有以下優勢 - 此代碼具有更高的可伸縮性。 只需將行,列值(例如5,9)或空格字符更改為“*”並檢查輸出。 你可以玩它。
我建議你使用@Sand給出的答案來理解For循環然后檢查這個答案以了解如何優化它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.