I'm trying to do a Josephus problem, but I'm not allowed to use code snippets from other people. With this in mind, I have 27 errors in my code, but can't figure out how to fix it. Would you wonderful people explain to me why it won't compile. I want to see if my logic is flawed, but I can't test it because it won't compile. Any other tips are more than welcome! Here is my code:
import java.util.*;
public class Josephus
{
public class Link
{
public int num;
public Link next;
public Link (int d)
{
num = d;
next = null;
}
}
public class Main
{
Scanner in = new Scanner(System.in);
System.out.println("How many players");
int numPlayers = in.nextInt();
Link first, last;
first = last = new Link (1);
for(int k=2; k<=numPlayers; k++)
{
last.next = new Link(k);
last = last.next;
}
last.next = first;
System.out.println("How many skips");
int m = in.nextInt();
for (int g=0; g<numPlayers; g++)
{
for (int k=0; k<=m; k++);
{
last = last.next;
}
last.next;
last = last.next;
}
}
}
I cleaned up a bit your code so it compiles, you might be better off with two classes
Josephus.java
import java.util.Scanner;
public class Josephus {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("How many players");
int numPlayers = in.nextInt();
Link first = new Link(1);
Link last = new Link(1);
for (int k = 2; k <= numPlayers; k++) {
last.next = new Link(k);
last = last.next;
}
last.next = first;
first.next = last;
System.out.println("How many skips");
int m = in.nextInt();
for (int g = 0; g < numPlayers; g++) {
for (int k = 0; k <= m; k++)
{
last = last.next;
}
// last.next;
last = last.next;
}
in.close();
}
}
and Link.java
public class Link {
public int num;
public Link next;
public Link(int d) {
num = d;
next = null;
}
}
This compiles and accepts input, then throws an error. I haven't fixed that since I don't know exactly what you're trying to achieve.
Changes:
All that you should need now is to implement the Josephus logic inside the nested loops and output your results (if desired) all of which should be quite language agnostic.