今天笔试有道这样的题
用程序输出下面的序列:
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
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={'我','爱','你'};
就得到如下结果:
我
爱 你
你 我 爱
我 爱 你 我
爱 你 我 爱 你
你 我 爱 你 我 爱
我 爱 你 我 爱 你 我
爱 你
你 我 爱
我 爱 你 我
爱 你 我 爱 你
你 我 爱 你 我 爱
我 爱 你 我 爱 你 我