有人可以幫我在kotlin中使用for回圈制作這樣的星形圖案嗎?我已經嘗試過了,但我認為我的代碼太長了。有人能幫我嗎?
x 星形圖案
fun fifthPyramid(){
for(i in 1..13){
if(i==1||i==13){
print("*")
}else
print(" ")
}
println("")
for(i in 1..13){
if(i==2||i==12){
print("*")
}else
print(" ")
}
println("")
for(i in 1..13){
if(i==3||i==11){
print("*")
}else
print(" ")
}
println("")
for(i in 1..13){
if(i==4||i==10){
print("*")
}else
print(" ")
}
println("")
for(i in 1..13){
if(i==5||i==9){
print("*")
}else
print(" ")
}
}
uj5u.com熱心網友回復:
星形圖案正好由N * 2 - 1行和列組成。所以外回圈和內回圈將一直運行到count = N * 2 - 1
fun main() {
var starCount = 5;
val count = starCount * 2 - 1;
for(i in 1..count){
for(j in 1..count){
if(j==i || (j==count - i 1))
{
print("*");
}
else
{
print(" ");
}
}
println("")
}
}
uj5u.com熱心網友回復:
識別關于行和列的模式。當行和列相同,或者列的行和列相同時,你放一個 *。
fun printX(size: Int, char: Char) {
repeat(size) { row ->
repeat(size) { col ->
print(if (row == col || row == (size - col - 1)) char else ' ')
}
println()
}
}
fun main() {
printX(7, '*')
}
uj5u.com熱心網友回復:
您可以撰寫 afun以 aInt和 aChar作為引數,然后使用回圈來構建每一行并列印它。
基本上是這樣的:
fun printX(heightWidth: Int, symbol: Char) {
// iterate the heigth in order to build up each line (top->down)
for (i in 0 until heightWidth) {
/*
build up an array of Chars (representing a line)
with the desired size (length of a line)
filled up with whitespaces by default
*/
var line = CharArray(heightWidth) { ' ' }
// then replace whitespaces at the desired indexes by the symbol
line[i] = symbol // one from left to right
line[line.size - i - 1] = symbol // and one from right to left
// and print the result
println(line)
}
}
你可以拋出一個Exception負值,heightWidth因為如果你不這樣做,它們會造成麻煩。并且可能禁止 0、1 和 2,因為盡管它們會產生有效的輸出,但該輸出很難被視為X。甚至 3 和 4 的輸出也相當難看;-)
然而,這里的輸出printX(7, '7'):
7 7
7 7
7 7
7
7 7
7 7
7 7
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/432432.html
上一篇:django-React-Axios:資料未保存在資料庫中
下一篇:正則運算式分支名稱模式有條件
