能否用面向对象的方法实现
猴子选大王 n个猴子围成一圈,从第一个猴子开始重复一二三,数到三的猴子从圈子中出来,最后剩下的一个猴子就是大王。编程模拟。此过程,输出猴子出圈的编号次序和大王的编号。 程序代码:
import java.util.*; class Monkey { static int number = 0; private int no; public Monkey() { number++; this.no = number; } public String toString() { return "Monkey" + no; } } public class MonkeyKing { public LinkedList<Monkey> list = new LinkedList<Monkey>(); public MonkeyKing(int n) { for (int i=0; i<n; i++) { list.add(new Monkey()); } } public void selectKing() { list = parseList(list,3); System.out.println("The monkey king is " + list.get(1)); } public static LinkedList parseList(LinkedList list,int pos) { while(list.size()>pos-1){ for (int i = 0; i < pos-1; i++) { list.addLast(list.getFirst()); list.remove(i); } list.removeFirst(); System.out.println(list); } return list; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); MonkeyKing mk = new MonkeyKing(n); mk.selectKing(); } }