How to write a Java method?

2008-04-17 8:39 am
Any one please help me with print this pattern in java.

Question : Write a Java method call PrintPattern which take in two character ch1 and ch2 and an integer n.

Calling PrintPattern('*', '#', 5) will print out following pattern. For example, ('*' move in Right side is a one line)
*#*#*
#*#*
*#*
#*
*
Calling PrintPattern ('?', '+', 4) will print out following pattern
('+' move to Right side is a one line)
?+?+
+?+
?+
+

(Hint: using two for/while loops to print out following pattern on the screen.)

回答 (1)

2008-04-17 8:47 am
✔ 最佳答案
You want to use nested for loops.

public void PrintPattern(char ch1, char ch2, int num)
{
for(int i=0;i<num;i++)
{
for(int j=i;j<num;j++)
{
if(j%2==0)
System.out.print(ch2);
else
System.out.print(ch1);
}
System.out.print("\n");
}
}
}


收錄日期: 2021-05-02 19:04:20
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20080417003926AAJsWhC

檢視 Wayback Machine 備份