本帖最后由 陈兆辉 于 2014-9-23 10:32 编辑
测试题,猫狗鱼过河问题。
我写了内部类,因为感觉过河和判断安全都是老农的动作,应该是老农的类提供。但是写完了,看网上其他人写的,没有这么做的,都是这届放到主函数里面。我这会不会有问题啊?- package com.itheima;
- import java.util.*;
- public class Test10 {
- //定义一个老农的内部类,拥有一系列的方法,为了给主函数调用,使用static修饰
- static class Peasant {
- //过河方法,接收河两岸(起点和终点)两个存储动物的集合
- void acrossRiver(List<String> starting,List<String> destination){
- while(true){
- //定义一个变量存储老农携带的动物
- String animal;
- int index;
- //从起点集合中选择一个动物,直到确保剩余的动物安全时停止循环
- do{
- index = new Random().nextInt(starting.size());//产生一个随机数
- animal = starting.remove(index);
- System.out.println("starting:老农选择了"+animal);
- }while(!isSafe(starting,animal));
- System.out.println("老农最终选择"+animal+"一起过河");
- //将所带的动物放到终点的动物集合中。
- destination.add(animal);
- animal = null;
- //如果终点的动物集合中存了3个动物,则结束循环
- if(destination.size()==3){
- System.out.println("老农成功过河!");
- break;
- }
- //判断对岸是否安全,安全则独自返回,不安全则带一个动物返回,直至安全。
- if(!isSafe(destination,animal)){ //此处传入的animal为null,避免重复加入某个动物的错误
-
- System.out.println("destination:对岸不安全,老农准备带一个动物返回");
- do{
- index = new Random().nextInt(destination.size());
- animal = destination.remove(index);
- System.out.println("老农准备带"+animal+"返回");
- }while(!isSafe(destination,animal));
- System.out.println("老农最终选择了"+animal+"一起返回");
- starting.add(animal);//返回,将携带的动物放回起点集合
- }
- else{
- System.out.println("对岸安全,老农独自返回。");
- }
- }
- }
-
- boolean isSafe(List<String> animals,String animal){
- boolean safe = true;
- //如果不安全,把标记改为假
- if(animals.contains("cat") && animals.size()>1){
- //如果携带了动物,就把动物放回去。
- if(!(animal==null))
- animals.add(animal);
- safe = false;
- }
- return safe;
- }
-
- }
-
- //主函数,创建起点动物集合,添加三种动物进去。
- public static void main(String args[]){
- Peasant peasant = new Peasant();
- List<String> starting = new ArrayList<String>();
- starting.add("dog");
- starting.add("cat");
- starting.add("fish");
- peasant.acrossRiver(starting, new ArrayList<String>());
- }
-
- }
复制代码
|
|