求大神写一个array的小程序(java)
用1demensional来体现2demensional,要求输入一个整数A,A是2-demensionalarray(用O填充)的长和宽,然后要求输入两个整数x和y,如...
用1 demensional来体现2 demensional , 要求输入一个整数A,A是2-demensional array(用O填充)的长和宽,然后要求输入两个整数x和y,如果xy大于A,要求重新输入,放一个X在输入位置(x,y),如果位置已经是X了,提示位置已经占用。 一直重复输入,直到输入-1,提示end。
(只能用1demensional array来表现2demensional array)
output:
Please enter A: 5 [enter]
Creating 5 x 5 board...
Please enter x: 3 [enter]
Please enter y: 4 [enter]
Show location (3, 4)...
OOOOO
OOOOO
OOOOO
OOXOO
OOOOO
**********************
Please enter x: 4 [enter]
Please enter y: 1 [enter]
Marking location (4, 1)...
OOOXO
OOOOO
OOOOO
OOXOO
OOOOO
***********************
Please enter x: -1 [enter]
End 展开
(只能用1demensional array来表现2demensional array)
output:
Please enter A: 5 [enter]
Creating 5 x 5 board...
Please enter x: 3 [enter]
Please enter y: 4 [enter]
Show location (3, 4)...
OOOOO
OOOOO
OOOOO
OOXOO
OOOOO
**********************
Please enter x: 4 [enter]
Please enter y: 1 [enter]
Marking location (4, 1)...
OOOXO
OOOOO
OOOOO
OOXOO
OOOOO
***********************
Please enter x: -1 [enter]
End 展开
1个回答
展开全部
有点问题,就是示例中的下标是从1开始计算的,所以你要留意一下,并不是我代码写错了。
import java.util.Scanner;
public class OneDemenstionArrray {
private static Scanner sc;
private static char[] array = null;
private static int A;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.print("Please enter A: ");
A = sc.nextInt();
System.out.println(String.format("Creating %d x %d board...", A, A));
initArray();
Point p = null;
while(true) {
p = getPoint();
if(null == p) {
break;
}
if(array[(p.x - 1) * A + (p.y - 1)] == 'X') {
System.out.println("Position occupied"); // 位置被占用
} else {
array[(p.x - 1) * A + (p.y - 1)] = 'X';
System.out.println(String.format("Show location (%d, %d)...", p.x, p.y));
showArray();
}
}
System.out.println("End");
}
private static void initArray() {
array = new char[A * A];
for(int i = 0; i < A; i ++) {
for(int j = 0; j < A; j ++) {
array[i * A + j] = 'O';
}
}
}
private static void showArray() {
for(int j = 0; j < A; j ++) {
for(int i = 0; i < A; i ++) {
System.out.print(array[i * A + j]);
}
System.out.println();
}
}
private static Point getPoint() {
int x = 0, y = 0;
Point p = new Point();
do {
System.out.print("Please enter x: ");
x = sc.nextInt();
if(-1 == x) {
return null;
}
p.x = x;
} while(x > A || x <= 0); // 根据题目的演示,xy是1开始计算的,所以不存在0,下同
do {
System.out.print("Please enter y: ");
y = sc.nextInt();
if(-1 == y) {
return null;
}
p.y = y;
} while(y > A || y <= 0);
return p;
}
}
class Point {
public int x;
public int y;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询