一道笔试题的另一种玩法

 

今天笔试有道这样的题

用程序输出下面的序列:
1
2 3
3 1 2
1 2 3 1
2 3 1 2 3
3 1 2 3 1 2
1 2 3 1 2 3 1

 

当时自己写了这样的程序:

int i,j,firstNum;
for(i=0;i<7;i++)
{
	firstNum=i%3;
	for(j=0;j<i+1;j++)
	{
		System.out.print(firstNum%3+1);
		System.out.print(" ");//空格
		firstNum++;
	}
	System.out.println();
}
  

虽然简单,但是觉得有点余味不足,所以想来点面向对象,所以就回来写了下面的代码:

public class CharGenerator
{
	int current;
	final static char [] charSet={'1','2','3'};
	
	public CharGenerator()
	{
		current=0;
	}
	public char next()
	{
		char next=charSet[current];
		current=(current+1)%charSet.length;
		return next;
	}

	public void init(char startChar)
	{
		boolean isSuccessful=false;
		for (int i = 0; i < charSet.length; i++)
		{
			if(charSet[i]==startChar)
			{
				current=i;
				isSuccessful=true;
				break;
			}
		}
		if(!isSuccessful)
		{
			throw new IllegalArgumentException("没有此元素!");
		}
	}
}
 然后写个junit test:
	public void testGetNextPrintNum()
	{
		CharGenerator startCharGenerator=new CharGenerator();
		CharGenerator eachLineGenerator=new CharGenerator();
		for (int i = 1; i <=7; i++)
		{
			char startChar=startCharGenerator.next();
			eachLineGenerator.init(startChar);
			for (int j = 0; j < i; j++)
			{
				System.out.print(eachLineGenerator.next()+" ");
			}
			System.out.println();
		}	
	}
 新的程序容易修改,来输出不同的东西,而不再仅仅只是数字,将字符集改动一下:
final static char [] charSet={'我','爱','你'};
 
就得到如下结果

爱 你
你 我 爱
我 爱 你 我
爱 你 我 爱 你
你 我 爱 你 我 爱
我 爱 你 我 爱 你 我
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值