首页 > 编程语言 > 详细

小JAVA大世界之程序建模跳蚤实验

时间:2016-10-30 20:22:02      阅读:315      评论:0      收藏:0      [点我收藏+]

package com.chigoe;
//房子类
class House {
private int m;// 保存行数
private int n;// 保存列数
private int[][] a;

public House() { // 无参构造方法
m = 10;
n = 10;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
a[i][j] = 0;
}
}
public House(int m,int n){//带参构造方法
this.m=n;this.n=n;
a=new int[m][n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
a[i][j] = 0;
}
}
public int getM() {
return m;
}
public int getN() {
return n;
}
public int[][] getA() {
return a;
}
public int getElment(int i,int j){
return a[i][j];
}
public void setElment(int i,int j,int v){
a[i][j]=v;
}
//判断跳蚤是否经过了所以瓷砖
public boolean checkZero(){
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
if(a[i][j]==0){
return true;
}
}
return false;
}
//遍历数组
public void display(){
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
System.out.print(" "+a[i][j]+" ");
}
System.out.println();//满足一行瓷砖就换行
}
}

}

//跳蚤类
public class Tiaozao {

private static final int UP=0;
private static final int DOWN=1;
private static final int RIGHT=2;
private static final int LEFT=3;
private int x,y;
private int totals;//保存总的次数
private House ahouse;//表示此类的成员变量是自己本身,也就是自己的一个对象。
public Tiaozao(House h){
ahouse=h;
totals=0;
x=(int)(Math.random()*ahouse.getM());//应该是随机生成跳蚤的初始位置
y=(int)(Math.random()*ahouse.getN());

}
public int getTotals(){
return totals;
}
public boolean walk(int direction){
System.out.println("x="+x+",y="+y+"direction="+direction);
switch(direction){
case UP:if(y==0) return false;
else{
ahouse.setElment(x, y, ahouse.getElment(x, y)+1);
y=y-1;
return true;
}
case DOWN:if(y==ahouse.getN()-1) return false;
else{
ahouse.setElment(x, y, ahouse.getElment(x, y)+1);
y=y+1;
return true;
}
case LEFT:if(x==0) return false;
else{
ahouse.setElment(x, y, ahouse.getElment(x, y)+1);
x=x-1;
return true;
}
case RIGHT:if(x==ahouse.getM()-1) return false;
else{
ahouse.setElment(x, y, ahouse.getElment(x, y)+1);
x=x+1;
return true;
}

default:
System.out.println("非法移动");
return true;
}
}
public void move(){
int nexdirection;
boolean success;
do{
nexdirection=(int) (Math.random()*4);
success=walk(nexdirection);
if(success){
totals++;
}
}while(ahouse.checkZero());
}
public static void main(String[] args) {

House ahouse=new House(4,4);
Tiaozao atiaozao=new Tiaozao(ahouse);//将对象作为参数,引用数据传递
atiaozao.move();
ahouse.display();
System.out.println("totals ="+atiaozao.getTotals());

}

}

小JAVA大世界之程序建模跳蚤实验

原文:http://www.cnblogs.com/Manbestrong/p/6013680.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!