Hi I am trying to re create a soccer tournament and have been able to create the groups with a map but now would like to add the points to each country. Anyone got any good ideas? please see what i have done already.
import java.util.*;
class EuroGroupStages {
public static void main(String args[]) {
Map<String, Set<String>> groupA;
//public EuroGroupStages()
// {
groupA = new TreeMap<>();
// }
//public void addCountries(String aGroup)
// {
Scanner keyboard = new Scanner(System.in);
String aCountry, aGroup;
char anAnswer;
boolean flag = true;
while(flag)
{
Set<String> country = new HashSet<>();
System.out.print("Please enter the group name (A-D):");
aGroup = keyboard.next();
for(int i = 1; i < 5; i++)
{
System.out.print("Please enter a country");
aCountry = keyboard.next();
country.add(aCountry);
}
System.out.print("Do you want to continue? Y/N");
anAnswer = keyboard.findWithinHorizon(".", 0).charAt(0);
if(anAnswer == 'N' || anAnswer == 'n')
{
flag = false;
}
groupA.put(aGroup, country);
}
System.out.println(groupA);
keyboard.close();
// }
}
}
I guess you would be better off creating Group and Team classes. Each Group would then contain a Set/List/... (whatever suits the best) of Team objects.
In the Team class, you can provide an attribute that contains the points of that team in the group stage.
For your Group:
public class Group {
private String name;
private Set<Team> teams;
public Group(String name) {
this.name = name;
this.teams = new TreeSet<>();
}
public void addTeam(Team team) {
teams.add(team);
}
}
For your Team:
public class Team {
private String name;
private int points;
public Team(String name) {
this.name = name;
}
public void addPoints(int amount) {
this.points += amount;
}
}
Example use:
public class EuroGroupStages {
public static void main(String[] args) {
// Create group B
Group groupB = new Group("B");
// Create teams in group B
Team belgium = new Team("Belgium");
Team finland = new Team("Finland");
Team denmark = new Team("Denmark");
Team russia = new Team("Russia");
// Add teams of group B to group B
groupB.addTeam(belgium);
groupB.addTeam(finland);
groupB.addTeam(denmark);
groupB.addTeam(russia);
// First matches were played, Belgium and Finland won
belgium.addPoints(3);
finland.addPoints(3);
}
}
Note: I did not run this code, it was written on the fly but should give you some idea of how to solve your problem.
Related
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));
}
We want to design a simple tournament that consist of teams with name and citizenship. In this tournament, a set of matches is organized between invited teams and each match opposes two teams. The team with the highest score wins the match. If the result of the match is draw each team gets 1 point, the winning team gets 2 points and no point for the loser. We would like to get the total of points of a team in a tournament to know the winner. The winner is the one with the highest points.
So we managed to create three classes: Team, Match and Tournament and the main class.
In the main class we have this
public class ProgramTournaments {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//Defining each team
Team frTeam, inTeam, cnTeam;
//Creation of three objects (Teams)
frTeam = new Team("French Blue Team", "French"); // New Means I want to create an Object (frTeams)
inTeam = new Team("Indian Blue Team", "India");
cnTeam = new Team("Chinese Red Team", "China");
//Create a new Tournament
Tournament tournament = new Tournament();
//Invite teams to the tourname
tournament.inviteTeam(frTeam);
tournament.inviteTeam(inTeam);
tournament.inviteTeam(cnTeam);
//Add matches to Tournament
Match m1 = new Match(frTeam, inTeam, true);
Match m2 = new Match(frTeam, cnTeam, true);
Match m3 = new Match(inTeam, cnTeam, true);
tournament.addMatch(m1);
tournament.addMatch(m2);
tournament.addMatch(m3);
//Check If all matches Have been Pleayed
tournament.allMatchPlayed();
}
}
In the team class we did this
public class Team {
//Defining the attributes
private String name; //Private means it is limited only to this Class (team)
private String citizenship;
public String getName() {
return name;
}
public String getCitizenship() {
return citizenship;
}
// Constructor inorder to initialized values
public Team (String name, String citizenship){
this.name = name; //Initializing name of team
this.citizenship = citizenship; //Initializing name of Citizenship of team
}
//Printing to strings
#Override
public String toString() {
return "Team{" + "name=" + name + ", citizenship=" + citizenship + '}';
}
}
In the Match class we did this
public class Match {
private Team team1, team2;
private int scoreTeam1;
private int scoreTeam2;
private int pointTeam1, pointTeam2;
boolean play;
//Constructor
public Match(Team team1, Team team2, boolean play) {
this.team1 = team1;
this.team2 = team2;
this.scoreTeam1 = generateRandomScore();
this.scoreTeam2 = generateRandomScore();
this.play = play;
}
//All Methods
public int getScoreTeam1() {
return scoreTeam1;
}
public void setScoreTeam1(int scoreTeam1) {
this.scoreTeam1 = scoreTeam1;
}
public int getScoreTeam2() {
return scoreTeam2;
}
public void setScoreTeam2(int scoreTeam2) {
this.scoreTeam2 = scoreTeam2;
}
public Team getTeam1() {
return team1;
}
public void setTeam1(Team team1) {
this.team1 = team1;
}
public Team getTeam2() {
return team2;
}
public void setTeam2(Team team2) {
this.team2 = team2;
}
public boolean isPlay() {
return play;
}
public void setPlay(boolean play) {
this.play = play;
}
//Generate Random Score
private int generateRandomScore() {
Random random = new Random();
return random.nextInt(5);
}
public boolean draw() {
if (scoreTeam1 == scoreTeam2) {
pointTeam1 = 1;
pointTeam2 = 1;
return true;
}
return false;
}
public Team matchWinner() {
if (scoreTeam1 > scoreTeam2) {
pointTeam1 = 2;
pointTeam2 = 0;
return team1;
} else {
pointTeam2 = 2;
pointTeam1 = 0;
return team2;
}
}
}
In the Tournament Class we did this
public class Tournament {
private List<Team> ListOfTeams = new ArrayList<>();
private List<Match> ListOfMatches = new ArrayList<>();
//Methods
public void inviteTeam(Team team) { //Inviting Teams
ListOfTeams.add(team);
}
public void addMatch(Match m) {
ListOfMatches.add(m);
}
public boolean allMatchPlayed() {
for (Match match : ListOfMatches) {
if (match.isPlay() == false) {
return false;
}
}
return true;
}
public void tournamentWinner(){
for (Match match : ListOfMatches){
match.decideResult();
}
Comparator <Team> team = new Comparator<Team>(){
#override
public int compare(Team t1, Team t2){
return t1.getScore() - t2.getScore();
}
};
Collections.sort(ListOfTeams, t);
System.out.println("The winner of the tournament is: " + ListOfTeams);
}
}
So please, we are stuck at trying to implement the total points for each teams and to get the winner based on the total points
I would advice to move points member variable from Match to Team. The reason being that each team will have some points at any point of time, so it makes sense that each team has a points field.
Now you would make the following changes to the methods
Team.java
public class Team {
private int points;
// getters and setters for points
/* Rest of your class */
}
Match.java
We should combine your draw() and matchWinner() to one method say decideResult(), as own their own they make no sense.
public void decideResult() {
if (scoreTeam1 == scoreTeam2) {
team1.setPoints(team1.getPoints() + 1);
team2.setPoints(team2.getPoints() + 1);
} else if (scoreTeam1 > scoreTeam2) {
team1.setPoints(team1.getPoints() + 2);
} else {
team2.setPoints(team2.getPoints() + 2);
}
}
To find the winner you can just fetch the score from the respective Team object. For eg : frTeam.getPoints() and compare this with another countries .getPoints()
I am trying to create a program that has 3 Objects; Hotel, Room and Bed. Object Bed will hold information about the bed. Object Room will hold information about the room including how many beds it contains. Object Hotel will contain information about how many Rooms it contains.
my code for the Hotel class looks like this
public class Hotel {
private String name;
private boolean HasVacency = false;
public int numberOfRooms;
Room[] rooms = new Room[numberOfRooms + 1];
public Hotel() {
}
public void setRoom(int numberOfRooms) {
this.numberOfRooms = numberOfRooms;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
And the code for the test class where i create the hotel and declare the values looks like this
public static void main(String[] args) {
HotelTest t = new HotelTest();
t.getHotelInfo();
}
public void getHotelInfo() {
Hotel test = new Hotel();
int numberOfRooms;
int numberOfBeds;
String size;
Scanner input = new Scanner(System.in);
System.out.println("what is the name of the hotel");
String name = input.next();
test.setName(name);
System.out.println("how many rooms does the hotel have");
numberOfRooms = input.nextInt();
test.setRoom(numberOfRooms);
System.out.println(test.rooms.length);
for( int i = 0; i< test.numberOfRooms + 1; i++) {
System.out.println("how many beds does room " + (i + 1) + " have");
numberOfBeds = input.nextInt();
System.out.println(i);
test.rooms[i].setNumberOfBeds(numberOfBeds);
}
}
however i keep getting a null pointer when i try to set the value for the number of rooms in test. Sorry for the messy code
A few things to look at here. Your code breaks encapsulation (you have public members of your hotel class being accessed by other classes); you could make use of constructors to make things a bit neater; look at creating the hotel from its components upward instead of a top-down approach. I've included some sample code based on yours.
public class Hotel {
private final List<Room> rooms;
private final String name;
// constructor to initialize hotel with name and number of rooms
public Hotel(String name, List<String> rooms) {
this.name = name;
this.rooms = rooms;
}
public Room[] getRooms() {
return this.rooms;
}
public String getName() {
return this.name;
}
}
public class Room {
private final int beds;
// constructor to initialize a room with the number of beds it needs
public Room(int beds) {
this.beds = beds;
}
public int getBeds() {
return this.beds;
}
}
public void getHotelInfo() {
Scanner input = new Scanner(System.in);
System.out.println("what is the name of the hotel");
String name = input.next();
System.out.println("how many rooms does the hotel have");
int numberOfRooms = input.nextInt();
List<Room> rooms = new ArrayList<>();
for( int i = 0; i< numberOfRooms; i++) {
System.out.println("how many beds does room " + (i + 1) + " have");
int numberOfBeds = input.nextInt();
// create a room with the number of beds specified and add it to the list of rooms
Room room = new Room(numberOfBeds);
rooms.add(room);
}
Hotel hotel = new Hotel(name, rooms);
// from here on, if you want the hotel's name or its rooms, you can use the appropriate getter methods in the Hotel and Room classes
}
class Hotel {
private String name;
private boolean HasVacency = false;
public Hotel(int numberOfRooms) {
Room[] rooms = new Room[numberOfRooms + 1];
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
I modified your Hotel class. In your old code array of room were being initialized before you are updating numberOfRooms. Create Hotel object like this Hotel test = new Hotel(numberOfRooms);
I am implementing RISK/Conquer game in JAVA. During the start-up phase of the game, I have to assign countries to each and every player. Just like distributing of cards from deck one by one to each player in the round-robin fashion.
The relation between Country and Player :
One Country has One Player (One to One)
One Player has Many Country (One to Many)
So far, this is my code:
Player.java
public class Player {
public String name;
public int totalArmies;
public List<Country> assignedCountries;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTotalArmies() {
return totalArmies;
}
public void setTotalArmies(int totalArmies) {
this.totalArmies = totalArmies;
}
public List<Country> getAssignedCountries() {
return assignedCountries;
}
public void setAssignedCountries(List<Country> assignedCountries) {
this.assignedCountries = assignedCountries;
}
public Player(String name) {
super();
this.name = name;
}
startup.java
public class startup {
HashMap<Country, List<Country>> graphMap = new HashMap<>();
List<Country> neigNodesList = new ArrayList<>();
List<Country> neigNodesList1 = new ArrayList<>();
static List<Country> listofCountrytoAssignPlayers = new ArrayList<>();
static List<Player> player = new ArrayList<>();
public void startup() {
Country neig1 = new Country("ABC", 13, 14, "Asia");
neigNodesList.add(neig1);
Country neig2 = new Country("XYZ", 13, 14, "Asia");
neigNodesList.add(neig2);
Country country1 = new Country("MNP", 10, 11, "NorthAmerica");
Country country2 = new Country("QWERTY", 10, 11, "NorthAmerica");
Country country3 = new Country("IJK", 10, 11, "NorthAmerica");
graphMap.put(country1, neigNodesList);
graphMap.put(country2, neigNodesList1);
graphMap.put(country3, neigNodesList);
Iterator it = graphMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
Country keyCountry = (Country) pair.getKey();
listofCountrytoAssignPlayers.add(keyCountry);
List<Country> neiCountryList = (List<Country>) pair.getValue();
System.out.println("Country -->" + keyCountry.getCountryName());
System.out.print("------Neigh List--------");
System.out.println(graphMap.size());
for (Country county : neiCountryList) {
System.out.println(county.getCountryName());
}
System.out.println("-----------");
}// avoids a ConcurrentModificationException
}
public static void main(String args[]) {
startup s1= new startup();
s1.startup();
System.out.println("Enter number of players: ");
Scanner scanner = new Scanner(System.in);
int totalPlayers = scanner.nextInt();
List<Player> playerList = new ArrayList<Player>();
int i = 0;
while (i < totalPlayers) {
playerList.add(new Player("player" + i));
i++;
}
Collections.shuffle(listofCountrytoAssignPlayers);
for(Player player:playerList){
List<Country> countryforaPlayer = new ArrayList<>();
for(int k=0;k<playerList.size();k++)
{
countryforaPlayer.add(listofCountrytoAssignPlayers.get(k));
}
//player.setAssignedCountries(countryforaPlayer);
playerList.add(player);
}
}
}
I am getting the following error:
Enter number of players:
1
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at startupphase.startup.main(startup.java:86)
Process finished with exit code 1
What I am not getting is how to implement it, every algorithm/logic think of and try to implement it I am not getting the desired result.
Because you are modifying the collection (playerList) in the same loop, you are getting this ConcurrentModificationException.
Please go through this SO link.
You need to use
ListIterator
if you want to add any element in the same loop.
public static void check(){
String name;
System.out.println("Enter Customer Name to CHECK RESERVATION ticket for this Flight: ");
Scanner input = new Scanner(System.in);
name = input.nextLine();
if (list.contains(name)) { //WHY IS THIS ASKING FOR SEPARATE METHOD?
System.out.println(name +" has a Reservation on this FLight!");
menu();
}
I am trying to take an input and check to see if that input is in the Linked List. I am having problems though getting this to work right.
If I add the new method in my LinkedList.Java class it says it needs to define a variable for link. Below is what I have in entirety if it helps:
import java.util.Scanner;
class airline {
public static LinkedList list = new LinkedList();
public static void main(String[] args) {
list.addAirplane("Allen",501);
list.addAirplane("James",501);
list.addAirplane("Andrea",501);
list.addAirplane("Velvett",501);
list.addAirplane("Paul",501);
//Method sort the list after year the car was made
list.sortList();
menu();
//Method to print all objects in List
System.out.println(list.viewAll());
}
public static void menu(){
int menuOpt;
System.out.println("Airline Menu:");
System.out.println("1. Reserve a Ticket");
System.out.println("2. Cancel Reservations");
System.out.println("3. Check Reservations");
System.out.println("4. Display Airplanes on Flights");
Scanner input = new Scanner(System.in);
menuOpt=input.nextInt();
System.out.println(menuOpt);
switch (menuOpt){
case 1:
System.out.println("Reserve a Ticket");
reserveTick();
break;
case 2:
System.out.println("Cancel Reservations");
cancel();
break;
case 3:
System.out.println("Check Reservations");
check();
break;
case 4:
System.out.println("Passengers listed by Flights");
break;
default:
System.out.println("INVALID RESPONSE!");
menu();
break;
}
}
public static void reserveTick(){
String name;
System.out.println("Enter Customer Name to RESERVE ticket for this Flight: ");
Scanner input = new Scanner(System.in);
name = input.nextLine();
list.addAirplane(name,501);
System.out.println(name + " has been added to Flight Number 501");
menu();
}
public static void cancel(){
String name;
System.out.println("Enter Customer Name to CANCEL ticket for this Flight: ");
Scanner input = new Scanner(System.in);
name = input.nextLine();
list.remove(name, 501);
System.out.println(name + " has been REMOVED from Flight Number 501");
menu();
}
public static void check(){
String name;
System.out.println("Enter Customer Name to CHECK RESERVATION ticket for this Flight: ");
Scanner input = new Scanner(System.in);
name = input.nextLine();
if (list.contains(name)) {
System.out.println(name +" has a Reservation on this FLight!");
menu();
}
else {
System.out.println(name + " is not on this Flight!");
menu();
}
}
public static void listpassengers(){
list.sortList();
}
}
------------------------------------------------------------------
import java.util.*;
public class LinkedList
{
private AirplaneNode head = null;
public void addAirplane(String name , int hk)
{
//If head = null then create the first node
if(head == null)
{
head = new AirplaneNode(name,hk,null);
}
else
{
//If there are more than 1 node
head = new AirplaneNode(name,hk,head);
}
}
public void sortList()
{
boolean sorted = false;
while(!sorted)
{
sorted = true;
for(AirplaneNode cursor = head ; cursor.getNext() != null ; cursor = cursor.getNext())
{
if(cursor.getHk() < cursor.getNext().getHk())
{
String n = cursor.getName();
int hk = cursor.getHk();
cursor.setName(cursor.getNext().getName());
cursor.setHk(cursor.getNext().getHk());
cursor.getNext().setName(n);
cursor.getNext().setHk(hk);
sorted = false;
}
}
}
}
public String viewAll()
{
StringBuffer str = new StringBuffer();
for(AirplaneNode cursor = head ; cursor != null ; cursor = cursor.getNext())
{
str.append(cursor+"\n");
}
return new String(str);
}
}
--------------------------------------------------------------
public class AirplaneNode
{
private String name;
private int hk;
private AirplaneNode next;
public AirplaneNode(String name,int hk,AirplaneNode head)
{
this.name = name;
this.hk = hk;
this.next = head;
}
public AirplaneNode getNext()
{
return next;
}
public String getName()
{
return name;
}
public int getHk()
{
return hk;
}
public void setName(String in)
{
name = in;
}
public void setHk(int in)
{
hk = in;
}
public String toString()
{
return name + " " + hk ;
}
}
It seems as if you are creating a own class LinkedList in the top package here:
import java.util.*;
public class LinkedList
{
Since your method check() belongs in the airline class in the same package (and without any import of java.util.LinkedList) it will instead use the class you have created and that class doesn't implement any contains() method.
Declare your linked list this way:
public static LinkedList<String> list = new LinkedList<String>();
EDIT (based on your comment):
It looks like you want a list of flights, where each flight has a list of passenger names.
public class Flight implements Comparable<Flight> {
private List<String> mPassengers;
private final int mFlight;
private static final Collator sCollator = Collator.getInstance();
public Flight(int flight) {
mPassengers = new ArrayList<String>();
mFlight = flight;
}
public void sortPassengers() {
Collections.sort(mPassengers, sCollator);
}
public void addPassenger(String name) {
mPassengers.add(name);
}
public boolean removePassenger(String name) {
return mPassengers.remove(name);
}
public boolean hasPassenger(String name) {
return mPassengers.contains(name);
}
public String getFlight() { return mFlight; }
public int compareTo(Flight other) {
return mFlight - other.mFlight;
}
}
public static List<Flight> list = new LinkedList<Flight>();
public static void main(String[] args) {
Flight flight = new Flight(501);
flight.addPassenger("Allen");
// etc. for all flight 501 passengers
list.add(flight);
// repeat all the above for each flight number
}
You should be able to fill in the rest.