Because I have a thread and in my main program I want to create multiple threads of the same thing and I don't want the same name I tried to create unique names for each thread, e.g Player_1
, Player_2
, etc.
The thing is that it throws Duplicate local variable which I know that is because I use the same variable but I don't know how else I can create multiple names for a thread without me writing them. Here is the code.
Original Question
for (int l=0; l < noPlayers; l++){
String name = P + "" + (l + 1);
System.out.println(name);
Player name = new Player(TURN);
}
*The Player
is the thread which extends and TURN
is just a variable that will be processed.
Updated Question
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
class Referee extends Thread{
}
class Player extends Thread{
private int TURN;
public Player(int TURN) {
this.TURN = TURN;
}
public void run(){
int win = 0;
int lose = 0;
int draw = 0;
boolean k = true;
int j = 0;
for (j=0;j<=TURN;j++){
String [] arr = {"ROCK", "PAPER", "SCISSORS"};
Random Pick = new Random();
// randomly selects an index from the arr
int select = Pick.nextInt(arr.length);
// prints out the value at the randomly selected index
System.out.println("Random String selected: " + arr[select]);
}
}
}
public class MainApp {
public static void main(String[] args) {
int TURN = 0;
int No_Players = 0;
int i=0;
boolean h= true;
int j=0;
boolean k = true;
System.out.println("Welcome to Rock-paper-scissors, this is a tutorial of threads");
Scanner number = new Scanner( System.in );
System.out.println("Insert the number of players that will play");
while (h){
while (!number.hasNextInt()){
System.out.println("You didnt insert a number please try again");
number.next();
}
if(number.hasNextInt()){
j = number.nextInt();
if(j>1){
No_Players = j;
h=false;
}
else {
System.out.println("You need a value bigger than 1");
}
}
}
System.out.println("Please enter how many turns you want each player to play");
while (k){
while (!number.hasNextInt()){
System.out.println("You didnt insert a number please try again");
number.next();
}
if(number.hasNextInt()){
i = number.nextInt();
if(i>0){
TURN = i;
k=false;
}
else {
System.out.println("You need a value bigger than 0");
}
}
}
System.out.println("This game will have " + No_Players +" players and each one will have " + TURN + " turns");
Map<String,Thread> map = new HashMap<>();
for (int l = 0; i < No_Players; ++i) {
String name = "Player_" + i;
Player player = new Player(TURN);
player.setName(name);
map.put(name, player);
player.start();
}
}
}
**Posted the whole code because of some misunderstandings.