Java Code Overwrites Previous Entries of New Object Into Queue Array - java

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.

Related

Creating an printing an object that stores strings and integers in java

I have the following problem. Five classes are interacting with each other. Two of theme are doing fine. But with the creating of an Object of one class (Ticket) in my main class Event (getting user input from another class (UserInput), an processing this in the costructor) i have now problem to display the results.
Main class Event with main methode
import java.util.ArrayList;
public class Event {
private static String artistName;
private static int artistSalary;
private Language language;
private static ArrayList<String> trackList;
private InputReader inputReader;
private Ticket ticket;
private int amountOfTicketCategories;
private static Object[] ticketList;
private static int index;
public Event() {
}
public Event(Artist artist, Ticket ticket) {
artistName = artist.getArtistName();
artistSalary = artist.getArtistSalary();
trackList = artist.getArrayList();
for (index = 0; index < amountOfTicketCategories; index++) {
ticketList[index] = ticket.getTicket();
ticketList[index].toString();
}
}
public void chooseWhatToDefine() {
language = new Language();
language.whatToSpecify();
}
public void setTicketPrice(String ticketCategory, int ticketPrice) {
}
public void displayArtist(String artistName, int artistSalary) {
language = new Language();
language.displayArtistAndSalary(artistName, artistSalary);
}
public void displayTracklist(ArrayList<String> trackList) {
language = new Language();
language.displayTrackList(trackList);
}
public void displayTickets(Object[] ticketList) {
language = new Language();
language.displayTicket(ticketList);
}
public static void main(String[] args) {
Event event1 = new Event(new Artist(), new Ticket());
event1.displayArtist(artistName, artistSalary);
event1.displayTracklist(trackList);
event1.displayTickets(ticketList);
}
}
Ticket class with constructor that initalize the class with the user input comming from the InputReader class, and creates an object of Strings and Integers.
import java.util.Arrays;
public class Ticket {
private static String ticketCategory;
private static int ticketAmount;
private static int ticketPrice;
private InputReader inputReader;
private int amountOfTicketCategories;
private int index;
private Ticket[] ticketList;
public Ticket(String ticketCategory,int ticketAmount,int ticketPrice) {
}
public Ticket() {
inputReader = new InputReader();
inputReader.specifyTicketCategories();
ticketList = new Ticket[amountOfTicketCategories];
for (index = 0; index < amountOfTicketCategories; index++) {
inputReader.specifyTicket(ticketCategory, ticketAmount, ticketPrice);
ticketList[index] = new Ticket(ticketCategory, ticketAmount, ticketPrice);
}
}
public String toString() {
return("TicketCategory: " + ticketCategory + "Amount of Tickets: " + ticketAmount + "Ticket Price: " +ticketPrice);
}
public Object getTicket() {
return ticketList[index];
}
public int getAmountOfTicketCategories() {
amountOfTicketCategories = inputReader.specifyTicketCategories();
return amountOfTicketCategories;
}
}
InptReader class that processes the user input:
import java.util.ArrayList;
import java.util.Scanner;
public class InputReader {
private Scanner sc;
private Language language;
private ArrayList <String> tracks;
public InputReader() {
tracks = new ArrayList<String>();
language = new Language();
sc = new Scanner(System.in);
}
public int specifyTicketCategories() {
language.defineAmountOfTicketCategories();
return sc.nextInt();
}
public void specifyTicket(String ticketCategory, int ticketAmount, int ticketPrice) {
language.specifyTicketCategory();
ticketCategory = sc.next();
language.specifyTicketAmount();
ticketAmount = sc.nextInt();
language.specifyTicketPrice();
ticketPrice = sc.nextInt();
}
public int amountOfTickets() {
return sc.nextInt();
}
public int ticketPrice() {
return sc.nextInt();
}
public String readName() {
language.specifyArtist();
return sc.nextLine();
}
public int readInteger() {
language.specifyArtistSalary();
return sc.nextInt();
}
public void addTitle() {
int anzahlSongs = 3;
int index = 0;
while (index < anzahlSongs) {
language.specifyTrackList();
tracks.add(sc.nextLine());
index++;
}
}
public ArrayList<String> getArray() {
return tracks;
}
}
Language class that consists of the language statements
import java.util.ArrayList;
public class Language {
public Language () {
}
public void whatToSpecify() {
System.out.println("What would you like to specify fist? For Artist press 1, for Ticket press 2");
}
public void specifyArtist() {
System.out.println("Who is the artist? ");
}
public void specifyArtistSalary() {
System.out.println("How much does the artist earn? ");
}
public void displayTicket(Object[] ticketList) {
System.out.println("Ticketlist: " + ticketList);
}
public void displayArtistAndSalary(String artistName, int artistSalary) {
System.out.println("Artist: " + artistName + " " + "Salary: " + artistSalary);
}
public void displayTrackList(ArrayList<String> trackList) {
System.out.println("Tracklist: " + trackList);
}
public void specifyTicketCategory() {
System.out.println("What is the ticket category? ");
}
public void specifyTicketAmount() {
System.out.println("What ist the amount of tickets? ");
}
public void specifyTicketPrice() {
System.out.println("What is the price for your ticket?");
}
public void specifyTrackList() {
System.out.println("Add title: ");
}
public void defineAmountOfTicketCategories() {
System.out.println("How many ticket categories you like to set up?");
}
public void line() {
System.out.println("***********************************");
}
}
Artist class that that has creates an instance of an artist in the main class (same idea as for ticket) but with other variables and parameters.
import java.util.ArrayList;
public class Artist {
private int artistSalary;
private String artistName;
private InputReader inputReader;
ArrayList <String> trackList;
public Artist() {
inputReader = new InputReader();
artistName = inputReader.readName();
artistSalary = inputReader.readInteger();
inputReader.addTitle();
trackList = inputReader.getArray();
trackList.remove(2);
}
public String getArtistName() {
return artistName;
}
public int getArtistSalary() {
return artistSalary;
}
public ArrayList<String> getArrayList(){
return trackList;
}
}
Output in the console:
Add title:
Hello
Add title:
Hello
How many ticket categories you like to set up?
5
Artist: David Salary: 5000
Tracklist: [, Hello]
Ticketlist: null
First of all, in the Ticket class's constructor, you use the other constructor (The one with the 3 arguments), which has an empty body.
ticketList[index] = new Ticket(ticketCategory, ticketAmount, ticketPrice);
public Ticket(String ticketCategory,int ticketAmount,int ticketPrice) {
//this is empty
}
That means you're creating an object with.. nothing in it (null variables).
Try this:
public Ticket(String ticketCategory,int ticketAmount,int ticketPrice) {
this.ticketCategory = ticketCategory;
this.ticketAmount = ticketAmount;
this.ticketPrice = ticketPrice;
}
Then, your getTicket method is wrong. You never define the "index" integer in your Ticket class.
public Object getTicket() {
return ticketList[index];
}
Where "index" is undefined.
The ticketList should not be in the Ticket class => each time you create a Ticket instance, it will probably not be the same as the previous one.

How to modify code to add a quit option in the menu and keep it looping until it is called?

I am working on a Java text-based adventure game and want to change my code to add a Quit option as a fourth item and keep it looping until the user chooses to quit based on the respective choice. I originally had it so that it would run 10 times inside a while loop, but I decided I wanted the user to have control when they want to quit and end the program.
Here is what I have so far:
Game.java
public class Game {
private static Room library, study, ballroom, kitchen;
private static Room currentLocation;
public static void main(String[] args) {
initialSetupGame();
int rounds = 10;
while(rounds > 0) {
printNextRooms();
int nextRoomIndex = getUserRoomChoice();
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
rounds--;
}
}
public static void initialSetupGame() {
// Instantiate room objects of type Room
library = new Room("Library");
study = new Room("Study");
ballroom = new Room("Ballroom");
kitchen = new Room("Kitchen");
// Connect the objects to each other
library.addConnectedRoom(study);
library.addConnectedRoom(ballroom);
library.addConnectedRoom(kitchen);
study.addConnectedRoom(library);
study.addConnectedRoom(ballroom);
study.addConnectedRoom(kitchen);
ballroom.addConnectedRoom(library);
ballroom.addConnectedRoom(study);
ballroom.addConnectedRoom(kitchen);
kitchen.addConnectedRoom(library);
kitchen.addConnectedRoom(ballroom);
kitchen.addConnectedRoom(study);
// Prompt user for a name
Scanner input = new Scanner(System.in);
System.out.print("Please enter your name: ");
String playerName = input.nextLine();
System.out.println(playerName + "? Wow, that's a neat name!"
+ "\nWelcome to Aether Paradise, a game where you can explore"
+ " the the majestic hidden rooms of Aether. Let's begin!");
// Set the player to start in the library
currentLocation = library;
System.out.println(currentLocation.getDescription());
}
public static void printNextRooms() {
// Lists room objects as menu items
System.out.println("Where would you like to go next?");
currentLocation.printListOfNamesOfConnectedRooms();
}
public static int getUserRoomChoice() {
Scanner input = new Scanner(System.in);
System.out.println("{Select a number): ");
int choice = input.nextInt();
return choice - 1;
}
public static Room getNextRoom(int index) {
return currentLocation.getConnectedRoom(index);
}
public static void updateRoom(Room newRoom) {
currentLocation = newRoom;
System.out.println(currentLocation.getDescription());
}
}
Room.java
public class Room {
private String name;
private String description;
private ArrayList<Room> connectedRooms;
public Room(String roomName) {
this.name = roomName;
this.description = "";
connectedRooms = new ArrayList<>();
}
public Room(String roomName, String roomDescription) {
this.name = roomName;
this.description = roomDescription;
connectedRooms = new ArrayList<>();
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
// Add connected room to the array list
public void addConnectedRoom(Room connectedRoom) {
connectedRooms.add(connectedRoom);
}
public Room getConnectedRoom(int index) {
return connectedRooms.get(index);
}
public int getNumberOfConnectedRooms() {
return connectedRooms.size();
}
// Print the connected rooms to the console
public void printListOfNamesOfConnectedRooms() {
for(int index = 0; index < connectedRooms.size(); index++) {
Room r = connectedRooms.get(index);
String n = r.getName();
System.out.println((index + 1) + ". " + n);
}
}
}
Use java.util.Scanner to read input and check the entered value:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
initialSetupGame();
String reply;
do {
printNextRooms();
int nextRoomIndex = getUserRoomChoice();
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
System.out.print("Would you like to continue? [Y]es/[N]o");
reply = input.nextLine().toLowerCase();
} while ('y' == reply.charAt(0));
}

Why is there multiple output when I call from an arraylist?

import java.util.ArrayList;
class BryanList{
public static void main (String [] args)
{
ArrayList<String> alist=new ArrayList<String>();
alist.add("Bryan");
alist.add("18");
alist.add("Chicken Rice");
for (int i = 0; i <= alist.size(); i++) {
System.out.println ("My Name: "+alist.get(i));
System.out.println ("Age: "+alist.get(i));
System.out.println ("Favourite food: "+alist.get(i));
}
}
}
How come its not just displaying just one output instead there's 3 of the same output? Does anyone have any solution for this? Thanks.
If you want one time output then use generics class structure.
Create one class which you want to save records.
class Menu {
public int age;
public String name;
public String favFood;
}
You can create getter/setter method if you need. Otherwise just declare variables with public keyword.
Create one ArrayList which will store object of Menu class.
ArrayList<Menu> alist = new ArrayList<Menu>();
Menu menu = new Menu();
menu.name = "Bryan";
menu.age = 18;
menu.favFood = "Chicken Rice";
alist.add(menu);
Print output
for (int i = 0; i <= alist.size(); i++) {
Menu menu = alist.get(i);
System.out.println("My Name: " + menu.name);
System.out.println("Age: " + menu.age);
System.out.println("Favourite food: " + menu.favFood);
}
I updated your class with your requirement, please check.
class BryanList {
public static void main(String[] args) {
ArrayList<Menu> alist = new ArrayList<Menu>();
Menu menu = new Menu();
menu.name = "Bryan";
menu.age = 18;
menu.favFood = "Chicken Rice";
alist.add(menu);
for (int i = 0; i <= alist.size(); i++) {
Menu menu = alist.get(i);
System.out.println("My Name: " + menu.name);
System.out.println("Age: " + menu.age);
System.out.println("Favourite food: " + menu.favFood);
}
}
}
class Menu {
public int age;
public String name;
public String favFood;
}
Happy coding :)
Your loop check is happening on alist.size() which is in your case 3.
Now, in each iteration, it's printing alist.get(i) 3 times.
Suggestion:
Use POJO and add it to your list.
public class Person{
String name;
int age;
String favFood;
public getName(){
return name;
}
public getAge(){
return age;
}
public getFavFood(){
return favFood;
}
public setName(String name){
this.name = name;
}
public setName(int age){
this.age = age;
}
public setName(String favFood){
this.favFood = favFood;
}
}
And now, your code will work with simple modification.
public static void main (String [] args){
ArrayList<String> alist=new ArrayList<String>();
Person person = new Person();
person.setName("Bryan");
person.setAge(18);
person.setFavFood("Chicken Rice");
// If you want multiple person to add, you need to use loops, and that way you can keep creating person objects and add them to list.
// Suggesting, use separate method for that logic.
alist.add(person);
for (int i = 0; i <= alist.size(); i++) {
Person p = alist.get(i);
System.out.println ("My Name: "+ p.getName());
System.out.println ("Age: "+ p.getAge());
System.out.println ("Favourite food: "+ p.getFavFood());
}
}
Because your printing codes in a For loop. And loop is running 3 three times
alist.size()
means 3, you have 3 item in that list.
This can be your object class:
public class Table {
int age;
String name;
String food;
public Table(int age, String name, String food) {
this.age = age;
this.name = name;
this.food = food;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And fill arraylist with your object:
public static void main(String[] args) {
ArrayList<Table> alist = new ArrayList<>();
// this is how you fill
alist.add(new Table(18, "Bryan", "Rice");
for (int i = 0; i <= alist.size(); i++) {
System.out.println("AGE: " + alist.get(i).age);
//other stuff
}
}
import java.util.ArrayList;
public class HelloWorld {
public static void main(String []args) {
ArrayList<String> alist_name=new ArrayList<String>();
ArrayList<String> alist_value=new ArrayList<String>();
alist_name.add("My Name: ");
alist_name.add("Age: ");
alist_name.add("Favourite food: ");
alist_value.add("Bryan");
alist_value.add("18");
alist_value.add("Chicken Rice");
for (int i = 0; i < alist_name.size(); i++) {
System.out.println (alist_name.get(i)+alist_value.get(i));
}
}
}

Accessing array lists from threads

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 >

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() {}

Categories