This is a tool that you could use to generate an order for positions in any circumstance.
However, I am encountering infinite loops. How can I fix this?
import java.util.Random;
import java.util.Scanner;
public class WhoGoesFirst {
public static void main(String args[]) {
Random random = new Random();
Scanner input = new Scanner(System.in);
int MIN = 1;
int students = 0;
System.out.print("How many students do you have?");
students = input.nextInt();
int comp = random.nextInt(students - MIN + 1) + MIN;
for (int number = 0; number <= students; comp++) {
System.out.println(random);
}
}
}
Increment your number variable in the loop and it should fix the issue:
for (int number = 0; number <= students; number++, comp++) {
System.out.println(comp); //random is an object
}
You need to increment number:
import java.util.Random;
import java.util.Scanner;
public class WhoGoesFirst {
public static void main(String args[]) {
Random random = new Random();
Scanner input = new Scanner(System.in);
int MIN = 1;
int students = 0;
System.out.print("How many students do you have?");
students = input.nextInt();
int comp = random.nextInt(students - MIN + 1) + MIN;
for (int number = 0; number <= students; number++) {
System.out.println(random);
comp++;
}
}
}
Look at this line:
System.out.println(random);
This implementation is trying to print the random number generator, not the numbers themselves. There is a much easier solution, using the built-in Collections.shuffle :
List<Integer> positions = new ArrayList<Integer>(students);
for (int number = 0; number < students; number++)
positions.add(number);
Collections.shuffle(positions);
for (Integer number : positions)
System.out.println(number);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.