蛇行填数
显示效果如下:
1
3
4
2
5
8
6
7
9
package
Test;
import
java.io.BufferedReader;
import
java.io.IOException;
import
java.io.InputStreamReader;
public
class
Main {
public
static
void
main(String[] args)
throws
NumberFormatException,
IOException {
System.out.println(
"
请输入数组的大小:
"
);
BufferedReader br
=
new
BufferedReader(
new
InputStreamReader(System.in));
int
arraySize
=
Integer.parseInt(br.readLine());
int
[][] a
=
new
int
[arraySize][arraySize];
int
row
=
0
;
int
number
=
1
;
//
准备填充的数字
int
snakeLine
=
0
;
//
snakeLine代表斜行(蛇行)数,由于snakeLine将会用于数组下标的计算,所以从0开始计数
for
(; snakeLine
<
2
*
arraySize
-
1
; snakeLine
++
) {
if
(snakeLine
<
arraySize)
//
左上半部分
{
if
(snakeLine
%
2
!=
0
)
//
奇数斜行
{
for
(row
=
snakeLine; row
>=
0
; row
--
)
a[row][snakeLine
-
row]
=
number
++
;
}
else
{
for
(row
=
snakeLine; row
>=
0
; row
--
)
a[snakeLine
-
row][row]
=
number
++
;
}
}
else
{
//
右下半部分
if
(snakeLine
%
2
!=
0
) {
for
(row
=
arraySize
-
1
; row
>
snakeLine
-
arraySize; row
--
)
a[row][snakeLine
-
row]
=
number
++
;
}
else
{
for
(row
=
arraySize
-
1
; row
>
snakeLine
-
arraySize; row
--
)
a[snakeLine
-
row][row]
=
number
++
;
}
}
}
System.out.println(
"
Result as follows:\n
"
);
for
(row
=
0
; row
<
arraySize; row
++
) {
for
(number
=
0
; number
<
arraySize; number
++
) {
//
number此处作为数组的下标使用
System.out.print(a[row][number]
+
"
\t
"
);
}
System.out.println();
System.out.println();
}
}
}
马嘉楠
jianan.ma@gmail.com
posted on 2006-11-09 13:24
马嘉楠 阅读(483)
评论(0) 编辑 收藏 所属分类:
SoureCode