⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 snakeshapematrixserver.java

📁 java程序设计教程的源码
💻 JAVA
字号:
//(2)创建RMI服务器端的主程序,它必须连接服务器端的远程接口,其代码如例11-14所示。
//【例11-14】  RMI服务器端的主程序。
//程序清单11-14:  SnakeShapeMatrixServer.java
package rmi;

import java.rmi.*;
import java.rmi.server.*;

public class SnakeShapeMatrixServer extends UnicastRemoteObject implements
		SnakeShapeMatrix {// 需实现远程接口
	public static void main(String args[]) {// 主方法
		if (System.getSecurityManager() == null) {// 加载安全机制管理
			System.setSecurityManager(new RMISecurityManager());
		}
		try {// 创建服务器对象
			SnakeShapeMatrixServer snakeShapeMatrixServer = new SnakeShapeMatrixServer();
			// 在register注册该对象,localhost是服务器的名字
			Naming.rebind("//localhost/SnakeShapeMatrixServer",
					snakeShapeMatrixServer);
			System.out.println("已注册服务端进程:SnakeShapeMatrixServer !");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public SnakeShapeMatrixServer() throws RemoteException {// 构造方法
		super();
	}

	public int[][] getSnakeShapeMatrix(int size) {// 求解蛇形矩阵的方法
		int matrix[][] = new int[size][size];
		int max = size * size;
		int row = 0, col = 0;
		int direction = 0;
		for (int j = 1; j <= max; j++) {
			matrix[row][col] = j;
			switch (direction) {
			case 0:
				if (col + 1 >= size || matrix[row][col + 1] > 0) {
					direction += 1;
					direction %= 4;
					row += 1;
				} else {
					col = col + 1;
				}
				break;
			case 1:
				if (row + 1 >= size || matrix[row + 1][col] > 0) {
					direction += 1;
					direction %= 4;
					col -= 1;
				} else {
					row = row + 1;
				}
				break;
			case 2:
				if (col - 1 < 0 || matrix[row][col - 1] > 0) {
					direction += 1;
					direction %= 4;
					row = row - 1;
				} else {
					col = col - 1;
				}
				break;
			case 3:
				if (row - 1 < 0 || matrix[row - 1][col] > 0) {
					direction += 1;
					direction %= 4;
					col += 1;
				} else {
					row = row - 1;
				}
				break;
			default:
				System.out.println("ERROR!");
				System.exit(0);
			}
		}
		return matrix;
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -