对于Tapestry的作业,我必须在表格中显示一个钻石。这是我到目前为止所做的:
代码Index.java
public class Index
{
@Property
private Integer number;
@Property
private String [] table;
public Index() {
number = 9;
int temp = 0;
String tmp = "-";
table = new String[number * number];
if(singleCell == null)
singleCell="";
for (int i = 0; i < number; i++) {
for (int j = 0; j < number; j++) {
table[temp] = tmp;
temp++;
}
}
}
@OnEvent(component="diamond")
Object onDiamondLink() {
String swapValue = "*";
int sum = number / 2 ;
int x1 = number-1;
int sumY = number / 2;
int y1 = number+1;
int temp = x1 + sumY;
for (int i = 0; i < table.length; i++) {
table[i] = "-";
}
for (int i = 0; i < table.length; i++) {
if( i == sum) {
table[i] = swapValue;
sum = sum + x1;
}
if ( i == sumY ) {
table[i] = swapValue;
sumY = sumY + y1;
}
}
System.out.println("link diamond is activate");
return null;
}
public boolean isStartRow(){
return (myIndex%9 ==0);
}
public boolean isEndRow(){
return (myIndex%9 == 8);
}
public String getStartTR(){
return "<tr >";
}
public String getEndTR(){
return "</tr>";
}
index.tml的代码:
<t:actionlink t:id="diamond" >Diamond table</t:actionlink>
<br/>
<h1>Result:</h1>
<table border="1" >
<t:loop t:source="table" t:value="singleCell" index="MyIndex">
<t:if test="startRow">
<t:outputraw value="startTR"/>
</t:if>
<td width="20px">
${singleCell}
</td>
<t:if test="endRow">
<t:outputraw value="endTR"/>
</t:if>
</t:loop>
</table>
此代码生成此输出:
- - - - * - - - -
- - - * - * - - -
- - * - - - * - -
- * - - - - - * -
* - - - - - - - *
- - - - - - - * -
* - - - - - * - -
- * - - - * - - -
- - * - * - - - -
我需要的正确输出是:
- - - - * - - - -
- - - * - * - - -
- - * - - - * - -
- * - - - - - * -
* - - - - - - - *
- * - - - - - * -
- - * - - - * - -
- - - * - * - - -
- - - - * - - - -
任何想法都会有很大的帮助。
答案 0 :(得分:2)
想画一颗钻石?试试这个算法:
public class Diamond {
@Property
@Persist
private String diamond;
@SetupRender
init(){
int n,i,j,k;
do {
n = (int)(Math.random() * 10 + 3);
}while(n % 2 == 0);
diamond += ""+n+"<br\/>";
System.out.println();
for (i = 1; i <= n; i++){
for (k = n; k > i; k--)
diamond += "-";
for (j =1; j <= i; j++)
diamond += "*"+"-";
diamond += "<br\/>";
}
for (i = n; i > 0; i--){
for (k = n; k > i; k--)
diamond += "-";
for (j =1; j <= i; j++)
diamond += "*"+"-";
diamond += "<br\/>";
}
}
}
<强>更新强>
等一下,你想创建一个挂毯页面,它画出星号的钻石吗?
一种选择是使用:
<t:outputraw value="${diamond}"/>
您只需要将该字符串设置为页面的.java部分。(参见上面的代码已更新)
你的输出需要呈现为html,你可以使用我们给你的算法并插入html中断而不是println()
答案 1 :(得分:0)
这应该打印所需的输出:
public class Diamond
{
public static void main( String []args)
{
for(int i=0;i<9;i++){
for(int j=0;j<9;j++)
if( (i + j == 4 ) || (i-j == 4)||(i+j == 12) || (j-i == 4))
System.out.print("*");
else
System.out.print("-");
System.out.println();
}
}
}