rct妄想发明灵魂附身:求编程高手帮忙编写一个小JAVA程序

来源:百度文库 编辑:高校问答 时间:2024/04/29 19:49:01
要求用JAVA类方法编写,程序开始时在屏幕上输出30*30的由0组成的矩阵,运行后由系统提示要求输入方向(上、下、左、右)及数目,按照输入,在矩阵中移动,将经过的矩阵中的0变成1,句如同有个点在矩阵中走过,留下痕迹一样。

import java.util.Scanner;

public class Matrix
{
private int[][] target = new int[30][30];
private int rows = 0;
private int cols = 0;
public String direction = "";
private int moves = 0;

public Matrix()
{
for(int i = 0; i < 30; i++)
{
for (int n = 0; n<30; n++)
{
target[i][n] = 0;
}
}
}

public void print()
{
for(int i = 0; i < 30; i++)
{
for (int n = 0; n<30; n++)
{
System.out.print(target[i][n] + " ");
}
System.out.println();
}
}

public void input()
{
Scanner in = new Scanner(System.in);
System.out.println("please input the length of move");
moves = in.nextInt();
String waste = in.nextLine();
System.out.println("please input the direction of move");
direction = in.nextLine();
while(!((direction.equalsIgnoreCase("up") && (rows - moves >= 0)) || (direction.equalsIgnoreCase("down")&&( rows + moves < 30))
|| (direction.equalsIgnoreCase("left") && (cols - moves >= 0)) || (direction.equalsIgnoreCase("right") && (cols + moves < 30)))
&& !direction.equalsIgnoreCase("quit"))
{
System.out.println("error,out of boundary, please re-input");
System.out.println("please input the length of move");
moves = in.nextInt();
String waste1 = in.nextLine();
System.out.println("please input the direction of move");
direction = in.nextLine();
}
}

public void move()
{

for (int i = 1; i <= moves; i++)
{
if(direction.equalsIgnoreCase("up"))
{
target[rows - i] [cols] = 1;
}else if (direction.equalsIgnoreCase("down"))
{
target [rows + i][cols] = 1;
}else if(direction.equalsIgnoreCase("left"))
{
target [rows][cols - i] =1;
}else if(direction.equalsIgnoreCase("right"))
{
target [rows][cols + i] = 1;
}
}
}

public void update()
{
if(direction.equalsIgnoreCase("up"))
{
rows -= moves;
}else if (direction.equalsIgnoreCase("down"))
{
rows += moves;
}else if(direction.equalsIgnoreCase("left"))
{
cols -= moves;
}else if(direction.equalsIgnoreCase("right"))
{
cols += moves;
}
}
public static void main(String[] args)
{
Matrix test = new Matrix();
test.print();
while(!test.direction.equalsIgnoreCase("quit"))
{
test.input();
if (!test.direction.equalsIgnoreCase("quit"))
{ test.move();
test.update();
test.print();
}
}
}

}