我在這裏學到了很多東西,但是我有一個問題,我無法找到。帶嵌套環的鑽石顯示
我們的最後一項任務是要求我們在Java中使用嵌套For Loops來顯示鑽石。
程序必須使用由用戶輸入的符號,並得出如下:
%
% %
% % %
% % % %
% % % % %
% % % %
% % %
% %
%
到目前爲止,我僞編碼一個半三角形,然後我要編寫三角形的逆完成相反的一側,但我不能得到比這任何其他不增加符號的所需要的量:
*
**
***
****
*****
這是代碼:
String symbol1; //User input, symbol to utilize
Scanner Keyboard = new Scanner (System.in);
System.out.println("Enter the Symbol you wish to use: ");
symbol1 = Keyboard.next();
for (int i=0 ; i<5 ; i++)
{
for (int k=5 ; k > i; k--)
{
System.out.print(" ");
}
for (int j=0; j<=i; j++)
{
System.out.print(symbol1);
}
System.out.println();
}
}
}
任何輸入,非常感謝!
*編輯*
我想後我的最終代碼。 這可能很簡單,但我覺得很成功。 希望它能幫助某些人,比如我在這裏得到了幫助!
歡呼每一個人。
import java.util.Scanner;
公共類AlvaradoPgm04Bonus {
public static void main(String[] args) {
//繪製使用符號鑽石由用戶輸入
String symbol1; //User input, symbol to utilize
Scanner Keyboard = new Scanner (System.in); //New scanner
System.out.println("Enter the Symbol you wish to use: "); //Prompt user symbol input
symbol1 = Keyboard.next(); // Capture user input
for (int i=0 ; i<5 ; i++){ //Begin for loop - increase until int is 5 long
for (int k=8 ; k > i ; k--){ //nested loop - decrease space before int "i" (inverted invisible triangle)
System.out.print(" "); //print space from nested loop before symbol1
}
for (int j=0; j<=i; j++){ //nested loop - increase "j" until is equal to "i"
System.out.print(symbol1 + " "); //print symbol1 + space to form diamond
}
System.out.println(); //print above nested loop line by line
} //begin new loop - inverted triangle
for (int m = 4 ; m > 0 ; m--){ //decrease symbol by 1
for (int n = 8 ; n >= m ; n--){ //match increase of space "invisible" triangle next to symbol to form upside down triangle
System.out.print(" "); //print "invisible" triangle
}
for (int q = 0 ; q < m ; q++){ //nested loop to decrease symbol entered by user
System.out.print(symbol1 + " "); //print inverted triangle made of user's input
}
System.out.println(); //print the loop in new line.
} //end loop
}//end main
} //結束類
使用一個CHAR類型的符號,而不是字符串;除非你想支持比一個字符更寬的符號。 – Bathsheba
@ brano88我不是在尋找答案,而是在正確的道路上得到指導。我是新來的java,所以我仍然掌握了所有知識以及如何處理代碼以做我想做的事情。不管怎麼說,還是要謝謝你。任何反饋當然讚賞。 – Zethen