import java.util.InputMismatchException; import java.util.Scanner; public class Josephus { protected int numOfPers; // Number of persons protected boolean[] persons; // Circle of persons; true = live; false = dead public Josephus(int anumOfPers) { this.numOfPers = anumOfPers; this.persons = new boolean[this.numOfPers]; for(int i = 0; i < this.numOfPers; i++) { this.persons[i] = true; } } public int NextPersonWhoLive(int from) { for(int i = from; i < this.numOfPers; i++) { if(this.persons[i] == true) return i; } for(int i = 0; i < from - 1; i++) { if(this.persons[i] == true) return i; } return -1; } public void KillPerson(int per) { this.persons[per] = false; } public static void main(final String[] args) { int nop = -1; try { if(args.length >= 1) { nop = Integer.parseInt(args[0]); } else { Scanner scanner = new Scanner(System.in); System.out.print("Number of persons = "); System.out.flush(); nop = scanner.nextInt(); scanner.close(); } } catch (NumberFormatException e) { System.err.println("A number was specified in an invalid format: " + e.getMessage()); e.printStackTrace(System.err); System.exit(1); } catch (InputMismatchException e) { System.err.println("A number was specified in an invalid format."); e.printStackTrace(System.err); System.exit(1); } catch (Exception e) { System.err.println("An unknown error has occurred: " + e.getMessage()); e.printStackTrace(System.err); System.exit(1); } if(nop == -1) { System.err.println("The given number of people was either not understood by the program or was eaten."); System.exit(1); } else if (nop < -1) { System.err.println("A negative number was entered. The program cannot create a circle with a negative number of people."); } System.out.print("\n"); int sword = 0; int PersonToKill; Josephus circle = new Josephus(nop); while(true) { PersonToKill = circle.NextPersonWhoLive(sword + 1); if(PersonToKill == -1) break; circle.KillPerson(PersonToKill); System.out.println("Person " + (sword + 1) + " kills person " + (PersonToKill + 1) + ";"); sword = circle.NextPersonWhoLive(PersonToKill); System.out.println("Person " + (sword + 1) + " has the sword;\n"); } System.out.println("Person " + (sword + 1) + " survives."); } }