设计输出如下形式数值的函数
1
2 2
3 3 3
......
n n n n n
1,设计成递归结构的函数?
2,设计成循环结构的函数?(这个已经搞定,主要是第一个)
------解决方案--------------------public class Test {
public static void main(String[] args){
print(1, 6);
}
public static void print(int start, int max)
{
for (int i = 0; i < start; i++) {
System.out.print(start + "\t ");
}
if (start == max) {
return;
}
else {
System.out.println();
print(++start, max);
}
}
}
------解决方案--------------------我也来贴一个:
public class Pyramid
{
public static void print(int n)
{
if(n == 1)
System.out.print(n);
else
{
print(n - 1);
System.out.println();
for(int i = 0; i < n; i++)
System.out.print(n + "\t ");
}
}
public static void main(String[] args)
{
print(10);
System.out.println();
}
}
------解决方案--------------------不知可以不.
public class Test {
public static void main(String[] args) {
int n = 9;
Test test = new Test();
test.recursion(n);
}
public void recursion(int n) {
String str = " ";
if(n == 1) {
System.out.println(str + n);
}
else {
recursion(n-1);
for(int i=1;i <=n;i++) {
str += n;
}
System.out.println(str);
}
}
}
------解决方案--------------------都是高手啊,窜改一下楼上的,呵呵
public class Pyramid
{
public static void printrow(int i,int n)
{
if(i==n-1)
{
System.out.print(i + "\t ");
}
else {
printrow(i+1, n)
}
}
public static void print(int n)
{
if(n == 1)
System.out.print(n);
else
{
print(n - 1);
System.out.println();
printrow(i, n); }
}
public static void main(String[] args)
{
print(10);
System.out.println();
}
}
------解决方案--------------------public class Test4{
private static int num=1;
public static void print(int num,int times){
//int first=1;
for(int i=0;i <num;i++)
System.out.print(num+ " ");
System.out.println();
num++;
if(num <times)print(num,times);
}
public static void main(String[] args){
print(1,10);
}
}
我也来一个