Java基础教程 从C/C++到Java(四)

Java基础教程 从C/C++到Java(四)

内容大纲:

  1. 异常与异常机制
  2. 流与应用(略)
  3. MVC设计模式
  4. 控制反转
  5. 接口

异常与异常机制

java异常与异常机制与C++相同,均采用try-catch-finally的结构
代码如下

int[] array = new int[10];
    int idx;
    Scanner in = new Scanner(System.in);
    idx = in.nextInt();
    try {
        array[idx] = 0;
        System.out.println("有效下标");
    }catch(ArrayIndexOutOfBoundsException e) {
        System.out.println("非法的下标");
       threw e;//再次向外抛出
    }finally {
        System.out.println("finally最后一定会执行");
    }

Edit from B站dalao生之丶如舟的笔记

MVC设计模式

MVC设计模式是指Model(Data)、View和Control三者分离的程序设计模式,也是java程序项目的通用模式。以细胞自动机CellMachine为例,要求如下

  • 死亡:如果活着的邻居数量 < 2 或 > 3 则死亡
  • 新生:如果正好有三个邻居活着则新生
  • 其他情况则保持原状

运行效果图 实际上这个图会一直动
细胞自动机效果图
这个项目的结构如下
细胞自动机结构

  • View是将棋盘格显示出来的结构。
  • 棋盘格本身作为Model(Data),可以想象成一个二维对象数组,每一个格子中存放一个Cell类。
  • Cell类负责自身的死亡、新生状态。

这就是OB语言应有的MVC设计模式

文件结构如图所示
在这里插入图片描述

主类

package cellmachine;

import javax.swing.JFrame;

import cell.Cell;
import field.Field;
import field.View;

public class CellMachine {

	public static void main(String[] args) {
		Field field = new Field(30,30);
		for ( int row = 0; row<field.getHeight(); row++ ) {
			for ( int col = 0; col<field.getWidth(); col++ ) {
				field.place(row, col, new Cell());
			}
		}
		for ( int row = 0; row<field.getHeight(); row++ ) {
			for ( int col = 0; col<field.getWidth(); col++ ) {
				Cell cell = field.get(row, col);
				if ( Math.random() < 0.2 ) {
					cell.reborn();
				}
			}
		}
		
		//窗口
		View view = new View(field);
		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setResizable(false);
		frame.setTitle("Cells");
		frame.add(view);
		frame.pack();
		frame.setVisible(true);
		
		for ( int i=0; i<1000; i++ ) {
			for ( int row = 0; row<field.getHeight(); row++ ) {
				for ( int col = 0; col<field.getWidth(); col++ ) {
					Cell cell = field.get(row, col);
					Cell[] neighbour = field.getNeighbour(row, col);
					int numOfLive = 0;
					for ( Cell c : neighbour ) {
						if ( c.isAlive() ) {
							numOfLive++;
						}
					}
					System.out.print("["+row+"]["+col+"]:");
					System.out.print(cell.isAlive()?"live":"dead");
					System.out.print(":"+numOfLive+"-->");
					if ( cell.isAlive() ) {
						if ( numOfLive <2 || numOfLive >3 ) {
							cell.die();
							System.out.print("die");
						}
					} else if ( numOfLive == 3 ) {
						cell.reborn();
						System.out.print("reborn");
					}
					System.out.println();
				}
			}
			System.out.println("UPDATE");
			frame.repaint();
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}

棋盘格

package field;

import java.util.ArrayList;

import cell.Cell;

public class Field {
	private int width;
	private int height;
	private Cell[][] field;
	
	public Field(int width, int height) {
		this.width = width;
		this.height = height;
		field = new Cell[height][width];
	}
	
	public int getWidth() { return width; }
	public int getHeight() { return height; }
	
	public Cell place(int row, int col, Cell o) { //Cell o 细胞对象
		Cell ret = field[row][col];
		field[row][col] = o;
		return ret;
	}
	
	public Cell get(int row, int col) {
		return field[row][col];
	}
	
	public Cell[] getNeighbour(int row, int col) {
		ArrayList<Cell> list = new ArrayList<Cell>();
		for ( int i=-1; i<2; i++ ) {
			for ( int j=-1; j<2; j++ ) {
				int r = row+i;
				int c = col+j;
				if ( r >-1 && r<height && c>-1 && c<width && !(r== row && c == col) ) {
					list.add(field[r][c]);
				}
			}
		}
		return list.toArray(new Cell[list.size()]);
	}
	
	public void clear() {
		for ( int i=0; i<height; i++ ) {
			for ( int j=0; j<width; j++ ) {
				field[i][j] = null;
			}
		}
	}
	
}

Cell类

package cell;

import java.awt.Graphics;
 
public class Cell {
	private boolean alive = false;
	
	public void die() { alive = false; }
	public void reborn() { alive = true; }
	public boolean isAlive() { return alive; }
	
	public void draw(Graphics g, int x, int y, int size) {
		g.drawRect(x, y, size, size);
		if ( alive ) {
			g.fillRect(x, y, size, size);
		}
	}
}

View显示窗口类

package field;

import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

import cell.Cell;

public class View extends JPanel {
	private static final long serialVersionUID = -5258995676212660595L;
	private static final int GRID_SIZE = 16;
	private Field theField;
	
	public View(Field field) {
		theField = field;
	}

	@Override
	public void paint(Graphics g) {
		super.paint(g);
		for ( int row = 0; row<theField.getHeight(); row++ ) {
			for ( int col = 0; col<theField.getWidth(); col++ ) {
				Cell cell = theField.get(row, col);
				if ( cell != null ) {
					cell.draw(g, col*GRID_SIZE, row*GRID_SIZE, GRID_SIZE);
				}
			}
		}
	}

	@Override
	public Dimension getPreferredSize() {
		return new Dimension(theField.getWidth()*GRID_SIZE+1, theField.getHeight()*GRID_SIZE+1);
	}

	public static void main(String[] args) {
		Field field = new Field(10,10);
		for ( int row = 0; row<field.getHeight(); row++ ) {
			for ( int col = 0; col<field.getWidth(); col++ ) {
				field.place(row, col, new Cell());
			}
		}
		View view = new View(field);
		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setResizable(false);
		frame.setTitle("Cells");
		frame.add(view);
		frame.pack();
		frame.setVisible(true);
	}

}

Edit from https://github.com/lofang/xibao

控制反转

java的窗口frame采用swing,即容器-部件的结构,简易的用户交互程序类似于MFC,需要使用JFrame,JButton等java提供的类利用消息机制控制程序交互动作。此类程序设计内容日后有需要再继续深入了解。

接口

最后再稍稍提一下面向接口的编程方式

接口某种意义上是实现多继承的一种方式

  • 是一种纯的抽象类 表达概念和规范
  • 所有的成员函数都是抽象函数 所有的成员变量都是public static final
  • 在多人合作写大型程序时 接口机制是及其重要的
  • 设计程序时先定义接口再实现类
  • 接口可以继承接口 但不能继承类
  • 类的继承用extends,接口用implements
package cell;

import java.awt.Graphics;
 
public interface Cell {  // interface是接口的抽象类
	void draw(Graphics g, int x, int y, int size);
}

接口和类可以被子类同时“继承”

public class CelebralCell extends Brain implements Cell{
	// nothing
}

那么Celebral这Cell个类便是Brain的子类且是Cell的“子类”。和C++的多继承很像。

结语

学了四天的java,差不多把最基础的东西都学了(大概),在C++的基础上触类旁通感觉很好。因为属于实用主义,对于非程序员的我而言像线程、GUI设计等比较深入的东西一般都是使用到了才学,不然学久了就忘。
java总体给人感觉比较舒适,纯面向对象的编程风格也比较有意思。虽然简洁度和友好性不及python, 但相对于C++而言java显得思想上更加有秩序。
目前还不是很熟悉这种纯OB的编程风格,只能在日后的项目实践中锻炼了。
2019/7/11

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值