Accessing array lists from threads - java

I am making a multiplayer adventure game for my networking class. I have a client and a server, the server is multithreaded, and kicks off a new thread whenever it gets a new client connected. I have an array list that keeps track of the players to make sure that a new player isn't added. For some reason, when a new client connects, it takes the place of the old one as well as filling a new spot. Here is my code for this part
public class ClientHandler implements Runnable{
private AsynchronousSocketChannel clientChannel;
private static String command[];
private static String name;
private static GameCharacter character;
public ClientHandler(AsynchronousSocketChannel clientChannel)
{
this.clientChannel = clientChannel;
}
public void run(){
try{
System.out.println("Client Handler started for " + this.clientChannel);
System.out.println("Messages from Client: ");
while ((clientChannel != null) && clientChannel.isOpen()) {
ByteBuffer buffer = ByteBuffer.allocate(32);
Future result = clientChannel.read(buffer);
//Wait until buffer is ready
result.get();
buffer.flip();
String message = new String(buffer.array()).trim();
if(message == null || message.equals(""))
{
break;
}
System.out.println(message);
clientChannel.write(buffer);
try {
//Add the character to the routing table and the character table
if (message.contains("connect")) {
System.out.println("I'm here too?");
command = message.split(" ");
name = command[1];
AdventureServer.userInfo.put(name, this);
//Check to see if this game character exists
GameCharacter test;
boolean exists = false;
for(int i=0; i < AdventureServer.characters.size(); i++)
{
test = AdventureServer.characters.get(i);
System.out.println(test.getName());
System.out.println(this.name);
if(this.name.equals(test.getName()))
{
System.out.println("already Here");
exists = true;
}
}
if (exists == true)
{
//This person has connected to the server before
}
else {
//Create a game character
System.out.println("didn't exist before");
character = new GameCharacter(this.name, World.getRow(), World.getCol());
AdventureServer.characters.add(AdventureServer.userInfo.size() - 1, character);
System.out.println(AdventureServer.characters.get(0).getName() + " " +AdventureServer.characters.get(1).getName());
}
}
I understand that the print lines at the bottom will throw an error for the first client that connects, but that is not part of the issue.
And here is the declaration of the server
public class AdventureServer {
public static Map<String, ClientHandler> userInfo = new HashMap<>();
public static World world;
public static List<GameCharacter> characters = Collections.synchronizedList(new ArrayList<>());
public static void main(String args[]) {
//Create the games map that all of the users will exist on
world = new World(args[0]);
System.out.println("Asynchronous Chat Server Started");
try {
AsynchronousServerSocketChannel serverChannel = AsynchronousServerSocketChannel.open();
InetSocketAddress hostAddress = new InetSocketAddress("192.168.1.7", 5000);
serverChannel.bind(hostAddress);
while (true)
{
System.out.println("Waiting for client to connect");
Future acceptResult = serverChannel.accept();
AsynchronousSocketChannel clientChannel = (AsynchronousSocketChannel) acceptResult.get();
new Thread (new ClientHandler(clientChannel)).start();
}
} catch (Exception e) {
System.out.println("error interrupted");
e.printStackTrace();
System.exit(0);
}
}
}
Here is my constructor for game characters
public class GameCharacter {
public static int xpos;
public static int ypos;
private static String name;
private static int rowSize;
private static int columnSize;
static List<String> inventory = new ArrayList<>();
//Constructor
GameCharacter(String n, int rSize, int cSize)
{
xpos = 0;
ypos = 0;
name = n;
rowSize = rSize;
columnSize = cSize;
}
GameCharacter()
{
xpos = 0;
ypos = 0;
name = "billybob";
rowSize = 10;
columnSize = 10;
}

You can try:
public static volatile List<GameCharacter> characters = Collections.synchronizedList(new ArrayList<>());
Update:
The problem is that you are using a non synchronized HashMap userInfo.
Change that line from:
AdventureServer.characters.add(AdventureServer.userInfo.size() - 1, character);
To:
AdventureServer.characters.add(character);
Or make your HashMap Synchronized:
public static Map<String, ClientHandler> userInfo = Collections.synchronizedMap(new HashMap<>());
All those static declarations are making problems, you should remove them. In general you should avoid using static.
ClientHandler:
private static String command[];
private static String name;
private static GameCharacter character;
GameCharacter:
public static int xpos;
public static int ypos;
private static String name;
private static int rowSize;
private static int columnSize;
static List<String> inventory = new ArrayList<>();
Just a side note, this way your Class is more like Java code should look like:
import java.util.ArrayList;
import java.util.List;
public class GameCharacter {
private int xpos;
private int ypos;
private String name;
private int rowSize;
private int columnSize;
private List<String> inventory = new ArrayList<>();
// Constructor
GameCharacter(String n, int rSize, int cSize) {
this.xpos = 0;
this.ypos = 0;
this.name = n;
this.rowSize = rSize;
this.columnSize = cSize;
}
GameCharacter() {
this.xpos = 0;
this.ypos = 0;
this.name = "billybob";
this.rowSize = 10;
this.columnSize = 10;
}
public int getXpos() {
return xpos;
}
public void setXpos(int xpos) {
this.xpos = xpos;
}
public int getYpos() {
return ypos;
}
public void setYpos(int ypos) {
this.ypos = ypos;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRowSize() {
return rowSize;
}
public void setRowSize(int rowSize) {
this.rowSize = rowSize;
}
public int getColumnSize() {
return columnSize;
}
public void setColumnSize(int columnSize) {
this.columnSize = columnSize;
}
public List<String> getInventory() {
return inventory;
}
public void setInventory(List<String> inventory) {
this.inventory = inventory;
}
}

As a matter of readability, testability, and style, I would also recommend you not directly access data structures belonging to another class. Instead of
Adventureserver.characters.add(blah blah)
I would recommend making characters a private field of Adventureserver, and then creating a method to add or remove characters from it. In fact, I would be inclined not to make characters static -- there is no real advantage, and you might at some point want more than one Adventureserver running.
Sort of like so:
public class AdventureServer {
<...>
private List<GameCharacter> characters = Collections.synchronizedList(new ArrayList<>);
<...>
public void addCharacter(GameCharacter char) {
<... error checking ...>
characters.add(char);
}
public void removeCharacter(GameCharacter char) {
<... implementation ... >
}
public boolean isCharacterHere(GameCharacter char) {
}
public List<GameCharacter> getCharacters() {
<... you could either return characters here, or a copy of it,
depending upon how paranoid you want to be >

Related

Java Code Overwrites Previous Entries of New Object Into Queue Array

I am trying to write an algorithm that allows the user of the program to enter an order into a queue that is an array. I am able to insert the order and insert another order, however, every subsequent order I place overwrites my previous orders. There are still spots in the array where the orders were but they are all copies of the newest order. Here is my code:
//Class to define individual orders for queueOrders
class Order
{
//Global Variables
public static String name;
public static String order;
public static int orderNum;
//Constructor
public Order()
{
}
public Order(int orderNum)
{
this.orderNum = orderNum;
}
public Order(String name, String order)
{
this.name = name;
this.order = order;
}
public Order(String name, String order, int orderNum)
{
this.name = name;
this.order = order;
this.orderNum = orderNum;
}
//Getters and Setters
public static String getName()
{
return name;
}
public static void setName(String name)
{
Order.name = name;
}
public static String getOrder()
{
return order;
}
public static void setOrder(String order)
{
Order.order = order;
}
public static int getOrderNum()
{
return orderNum;
}
public static void setOrderNum(int orderNum)
{
Order.orderNum = orderNum;
}
}
//Class to define queue
class QueueOrders
{
//Global Variables
// private int nItems = 0;
private static int maxSize;
private static int numOfOrders = 0;
//Array of Orders objects
private static Order orders[];
private static int front;
private static int back;
//Constructor
public QueueOrders(int size)
{
maxSize = size;
orders = new Order[maxSize];
front = 0;
back = 0;
}
//Insert new order
public static void insertOrder(String name, String order)
{
//Variables
// int cntr = 1;
if(isFull())
{
System.out.println("There are too many orders."
+ " Remove some first. ");
}
else
{
// if(back == maxSize - 1)
// {
// back = 0;
// }
Order.setName(name);
Order.setOrder(order);
//// Order.name = name;
//// Order.order = order;
// Order.setOrderNum(cntr);
Order newOrder = new Order(name, order, (numOfOrders + 1));
//Add order to orders array
orders[back] = newOrder;
//front = numOfOrders - 1;
// cntr++;
back++;
numOfOrders++;
}
}
//These functions are in the main class of the program
public static void main(String[] args)
{
QueueOrders queue = new QueueOrders(100);
menu();
}
//Function to add an order to the queue
public static void addOrder()
{
//Variables
String xName;
String xOrders;
Scanner myScan = new Scanner(System.in);
try
{
//Message user
System.out.println("What is the three letter name for your order? ");
xName = myScanner.nextLine();
//Message user
System.out.println("What is your order? ");
xOrders = myScan.nextLine();
QueueOrders.insertOrder(xName, xOrders);
QueueOrders.displaySingleOrder();
System.out.println("Your order has been placed. ");
} catch (Exception e)
{
System.out.println("Was unable to insert your order");
}
}
The problem is that you are using static variables for order data:
public static String name;
public static String order;
public static int orderNum;
They are specific to class Order, not to objects Order order you are adding in the list. Remove the keyword static from those variables.
This implementation
public class Sample {
public String a;
public static String b;
public static void main(String[] args) {
Sample s1 = new Sample();
s1.a = "1a";
s1.b = "1b";
Sample s2 = new Sample();
s2.a = "2a";
s2.b = "2b"; // This one set Sample.b to "2b" because b is
// static and shared among all Sample objects (s1 and s2).
System.out.println(s1.a + " " + s1.b + " " + s2.a + " " + s2.b);
}
}
will print 1a 2b 2a 2b (not 1a 1b 2a 2b) because b is static and value "1b" is overwritten by s2.b = "2b".
See this article for more information.

how can I remove a room in arraylist Room by name?

I'm learning java. I have trouble about arraylist in my java program. How can I remove a room in arraylist in Room and count the number of rooms has the size smaller than 40. I just coded 2 methods which were removeRoom and countRoomBySize in class MyRoom. My code has error in Net Beans. Anyone help me to check this code, please. Thank so much. Here is my code
My Main class
public class MyMain {
public static void main(String[] args) {
//create a list of rooms
MyRoom m = new MyRoom();
m.addRoom(new Room("HB201L",35));
m.addRoom(new Room("HB401R",45));
m.addRoom(new Room("211",30));
m.sort();
m.list();
//1.
m.removeRoom("211");
m.list();
//2.
int c = m.countRoomBySize(40);
System.out.println(c);//2
}
}
Class Room
public class Room implements Comparable<Room> {
#Override
public int compareTo(Room o) {
return o.name.compareToIgnoreCase(this.name);
}
//instanced variables
private int size;
private String name;
public Room() {
name = "";
size = 0;
}
public Room(String name, int size) {
this.name = name;
this.size = size;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Class MyRoom
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class MyRoom implements IRoom {
List<Room> rooms;
public MyRoom() {
rooms = new ArrayList();
}
#Override
public void addRoom(Room r) {
//append r to the end of list rooms
rooms.add(r);
}
#Override
public void list() {
for (int i = 0; i < rooms.size(); i++) {
Room r = rooms.get(i);
System.out.printf("%-20s%-10d\n",r.getName(),r.getSize());
}
}
#Override
public void removeRoom(){
for (int i = 0; i < rooms.size(); i++) {
if(rooms.get(i).getName() == "211")
rooms.remove(rooms);
}
}
#Override
public int countRoomBySize(){
int s,i,n;
n = rooms.size();
s = 0;
for(i=0;i<n;i++) {
if(rooms.get(i).getSize() > 40)
s++;
}
return(s);
}
public void sort() {
Collections.sort(rooms);
}
}
Interface IRoom
public interface IRoom {
//only contain public members: constants and method declaration
public final int MAX = 10;
public void addRoom(Room r);
public void list();
public void removeRoom();
public int countRoomBySize();
}
interface A {
void f();
}
interface B extends A {
void g();
}
interface C {}
First change your interface IRoom like this :
public void removeRoom(String name);
public int countRoomBySize(int size);
In the MyRoom class change removeRoom method like this :
#Override
public void removeRoom(String name){
for (int i = 0; i < rooms.size(); i++) {
if(name.equalsIgnoreCase(rooms.get(i).getName())){
rooms.removeIf(r -> r.getName().equals(name));
System.out.println("Removed !");
}
}
}
And the countRoomBySize method like this :
#Override
public int countRoomBySize( int size){
int s,i,n;
n = rooms.size();
s = 0;
for(i=0;i<n;i++) {
if(rooms.get(i).getSize() > size)
s++;
}
return(s);
}
Best of luck !
removeRoom can be shortened to: rooms.remove(rooms.indexOf("211")) or perhaps even rooms.remove("211");
Nice that you are starting to learn java.
The simplest solution here is to put your room in an Hashmap and store the room number as key;
public class MyMain {
public static void main(String[] args) {
Hashmap<String,Room> rooms = new Hashmap();
rooms.add("211",new Room("HB201L",35);
rooms.add("HB401R",new Room("HB401R",45);
rooms.remove("211");
int size = rooms.size();
int smallRooms = calculateSmallRooms(rooms.values(),30);
}
private int calculateSmallRooms(Collection<Room> rooms, int minimalSize) {
int smallRooms = 0;
for(Room room: rooms) {
if (room.size < minimalSize) {
smallRooms++;
}
return smallRooms;
}

Creating a getCounter() method to count up when the method is called

I am trying to create a getCounter() method which will count upwards each time the getCounter() method is called. For example if the method is called 10 times then the output should be: 1,2,3...10.
This is the current code I have:
Main class:
public class JavaLab5 {
public static final int DEBUG = 0;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Student s[] = new Student[10];
s[0] = new MathStudent("Smith");
s[1] = new MathStudent("Jack");
s[2] = new MathStudent("Victor");
s[3] = new MathStudent("Mike");
s[4] = new ScienceStudent("Dave");
s[5] = new ScienceStudent("Oscar");
s[6] = new ScienceStudent("Peter");
s[7] = new ComputerStudent("Philip");
s[8] = new ComputerStudent("Shaun");
s[9] = new ComputerStudent("Scott");
for (int loop = 0; loop < 10; loop++) {
System.out.print(loop);
System.out.println(s[loop].getSubjects());
}
}
}
Student class:
public class Student {
String name;
int count
public static int instances = 0;
//Getters
public String getName() {
return this.name;
}
// Setters
public void setName(String name) {
if (JavaLab5.DEBUG > 3) System.out.println("In Student.setName. Name = "+ name);
this.name = name;
}
/**
* Default constructor. Populates name,age and gender
* with defaults
*/
public Student() {
instances++;
this.name = "Not Set";
}
/**
* Constructor with parameters
* #param name String with the name
*/
public Student(String name) {
this.name = name;
}
/**
* Destructor
* #throws Throwable
*/
protected void finalize() throws Throwable {
//do finalization here
instances--;
super.finalize(); //not necessary if extending Object.
}
public void getCounter() {
for (int x = 0; x < 10; x++) {
count++;
System.out.println(count);
}
}
public String toString () {
return this.name;
}
public String getSubjects() {
return this.getSubjects();
}
}
My question is how I can implement such a method to call it from my Main class.
Two possibilities :
You wish to count every time you call the function and have a fresh counter for every object
public class Student {
String name;
int count =0; // every object of class Student will have its own `count`
//rest of the declrataions / functions
public void getCounter() {
System.out.println(++count);
}
}
You wish one counter that counts up every time you call getCounter irrespective of the number of objects you have of the class Student
public class Student {
String name;
static int count = 0; //static so that multiple object instances of the class share the same `int count`
//rest of the declrataions / functions
public void getCounter() {
System.out.println(++count);
}
}
If your question is how to implement such a method, try this:
private int myCounter = 0;
//Use this line instead if you want a global counter for all Studen-Objects
//private static int myCounter = 0;
public void getCounter() {
System.out.println(myCounter);
myCounter++;
}
You state you want to count how many times a method was called. In addition you want to print a sequence of all numbers starting from 1 to the number of counted method calls. Addressing concurrency, my solution would be:
public class CountTracker {
private static final AtomicInteger counter = new AtomicInteger();
public static int count() {
return counter.incrementAndGet();
}
public static void printCounter() {
int count = counter.get();
if (count == 0) return;
StringBuilder builder = new StringBuilder();
for (int i = 1; i <= count; i++) builder.append(i).append(",");
builder.deleteCharAt(builder.length() - 1);
System.out.println(builder);
}
}
The method count() represents the method you want to track. I have no idea why your solution does include a class Student.
simply remove for loop in getCounter method
change :
public void getCounter() {
for (int x = 0; x < 10; x++) {
count++;
System.out.println(count);
}
}
to :
public void getCounter() {
System.out.println(count);
count++;
}

Add objects with random variables using a loop

I am trying to write a program where I ask to the user how many persons he wants to implement in this world. Afterwards, I would like as many person objects as the user answered. I defined a person class with a person constructor containing all person variables ( + getters/setters). After this, I tried to create a loop to assign values to my variables (most of them happen random). Currently, I set the number of instances I want to create to 20 (arbitrary).
This is my person class
public class Person implements Item {
public static final int MAX_AGE = 70;
public static final int MAX_SEX_APPEAL = 10;
public static final int MAX_AGRESSION_LEVEL = 10;
public static final int MAX_STRENGTH = 10;
private int id;
private int age;
private boolean gender;
private int sexAppeal;
private int agressionLevel;
private int strength;
private boolean isAlive;
public Person (int id, int age, boolean gender, int sexAppeal, int agressionLevel, int strength, boolean isAlive){
this.setId(id);
this.setAge(age);
this.setGender(gender);
this.setSexAppeal(sexAppeal);
this.setAgressionLevel(agressionLevel);
this.setStrength(strength);
this.setAlive(isAlive);
}
void getBorn () {
isAlive = true;
age = 0;
// a new people is born
// age = 0
// other variables: random
}
void die () {
isAlive = false;
// people die when they reach the max age
// people die when being on the same cell as vulcanos
// people can be murdered
// setAlive = false
}
void murder () {
// when 2 people with min agression level on the same land ==> weakest one dies
}
void move () {
// method to make people move
// random (only to adjucant fields)
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
public int getSexAppeal() {
return sexAppeal;
}
public void setSexAppeal(int sexAppeal) {
this.sexAppeal = sexAppeal;
}
public int getAgressionLevel() {
return agressionLevel;
}
public void setAgressionLevel(int agressionLevel) {
this.agressionLevel = agressionLevel;
}
public int getStrength() {
return strength;
}
public void setStrength(int strength) {
this.strength = strength;
}
public boolean isAlive() {
return isAlive;
}
public void setAlive(boolean isAlive) {
this.isAlive = isAlive;
}
}
And this is my "test class" where I try to create 20 instances :
import java.util.concurrent.ThreadLocalRandom;
public class test {
public static void main(String[] args) {
for (int i = 0; i < 20; i ++) {
Person person(i) = new Person();
person.setId(i);
person.setAge(ThreadLocalRandom.current().nextInt(0, Person.MAX_AGE + 1));
person.setGender((Math.random() < 0.5));
person.setSexAppeal(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAgressionLevel(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setStrength(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAlive(true);
}
}
}
However, I am getting the following error at this line
Person person(i) = new Person();
The constructor Person () is undefined
Type mismatch: cannot convert from Person to int
I understand those errors but I don't know another way to become to the result I want to achieve
You should make a list and just add the created persons to it.
public class test {
public static void main(String[] args) {
List<Person> persons = new ArrayList<>(); // create a list to store the generated persons
for (int i = 0; i < 20; i++) {
Person person = new Person(); // generate a person
person.setId(i);
person.setAge(ThreadLocalRandom.current().nextInt(0, Person.MAX_AGE + 1));
person.setGender((Math.random() < 0.5));
person.setSexAppeal(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAgressionLevel(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setStrength(ThreadLocalRandom.current().nextInt(0, Person.MAX_SEX_APPEAL + 1));
person.setAlive(true);
persons.add(person); /// add the generated person to the list
}
}
}
Also if you want to call the Person constructor without parameters the class must have a constructor that takes no parameters.
public Person() {}

Java 2 new objects mess together

I have made a new object called Game:
public class Game {
private String gamenaam;
private String bungeenaam;
private int poort;
private int minplayers;
private int maxplayers;
private static GameState gamestate = GameState.Ingame;
public Game(String naam) {
this.gamenaam = naam;
setAlles();
}
public String getGameNaam() {
return this.gamenaam;
}
public String getBungeeNaam() {
return bungeenaam;
}
public int getPoort() {
return poort;
}
public int getMinPlayers() {
return minplayers;
}
public int getMaxPlayers() {
return maxplayers;
}
public GameState getCurrentState() {
//System.out.print(gamenaam + ":" + MySQL.getGameState(getGameNaam()) + ":" + gamestate);
return gamestate;
}
public void setCurrecntState(GameState state) {
gamestate = state;
}
private void setAlles() {
bungeenaam = MySQL.getBungeeNaam(this.gamenaam);
poort = MySQL.getPoort(this.gamenaam);
minplayers = MySQL.getMinPlayer(this.gamenaam);
maxplayers = MySQL.getMaxPlayer(this.gamenaam);
//gamestate = MySQL.getGameState(this.gamenaam);
}
}
I store everything in an public static HashMap<Location, Game> gameSigns = new HashMap<Location, Game>(); map
Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(Bukkit.getPluginManager().getPlugin("SCGameHost"), new Runnable() {
#Override
public void run() {
for(Map.Entry<Location, Game> entry: Main.gameSigns.entrySet()){
Game game = entry.getValue();
if(game.getGameNaam().equalsIgnoreCase("Heks")) {
System.out.print(game.getGameNaam()+" is changed to FINISHED");
game.setCurrecntState(GameState.Finished);
}else {
game.setCurrecntState(GameState.Maintenance);
}
}
}
}, 10 *20L, 10 *20L);
I have 2 things in the gameSigns HashMap Heks and Snowball.
When I change Heks to GameState.Finished snowball is also being changed.
It is because the variable gamestate is static, so it is shared between all the instances of the Game class. Remove the word static if you want separate values for different instances.

Categories