码迷,mamicode.com
首页 > 编程语言 > 详细

约瑟夫环 java 对象数组实现

时间:2015-04-19 11:29:52      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

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类中自带了编号。

欢迎评论,互相交流!

转载请注明出处!谢谢

约瑟夫环 java 对象数组实现

标签:

原文地址:http://www.cnblogs.com/lihang2015/p/4438717.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!