标签:
import java.util.Scanner; class Person{ String name; int seqno; Person(String _name, int _seqno){ name = _name; seqno = _seqno; } } public class JosephCircle { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in); System.out.println("------请输入总人数------"); int totalNum = scanner.nextInt(); System.out.println("----请输入报数的大小----"); int outNum = scanner.nextInt(); String[] name = new String[totalNum]; System.out.println("----请输入"+totalNum+"个人的名字,以回车键结束----"); for(int i = 0; i < totalNum+1; i++){ String str = scanner.nextLine(); if(i == 0) continue; name[i-1] = str; } scanner.close(); JoseCiCircle(totalNum, outNum, name); } private static void JoseCiCircle(int totalNum, int outNum, String[] name) { Person[] ps = new Person[totalNum]; for(int i = 0; i < totalNum; i++){ Person p = new Person(name[i], i+1); ps[i] = p; } int pre = 0; int currentNum = totalNum; while(currentNum > 0){ pre = (pre + outNum - 1) % currentNum; System.out.println("----"+ps[pre].seqno + "号已出局----"); ps = adjust(ps, pre, currentNum); currentNum--; } } private static Person[] adjust(Person[] ps, int pre, int currentNum) { // TODO Auto-generated method stub for(int i = pre; i < currentNum - 1; i++){ ps[i] = ps[i+1]; } return ps; } }
这是用数组实现约瑟夫环,用到了对象数组Person[],Person类中自带了编号。
欢迎评论,互相交流!
转载请注明出处!谢谢
标签:
原文地址:http://www.cnblogs.com/lihang2015/p/4438717.html