How to declare an object array length within another object - java

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);

Related

adding extra to a Map

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.

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));
}

To make the object variable private in another class

I have written the code this expected output:
Sample input :
Enter the passenger name:
Priya
Enter the gender(M or F / m or f):
F
Enter the age:
61
Enter the ticket no:
140
Enter the ticket price:
500.0
Sample Output 1 :
Ticket no:143
Passenger Name:Priya
Price of a ticket : 500.0
Total Amount : 375.0
I have to change the total amount value based on the age and gender for which I have written function.
My code:
Person.java
public class Person {
private String name;
private char gender;
private int age;
public void setName(String name ){
this.name = name;
}
public void setGender(char gender){
this.gender = gender ;
}
public void setAge(int age ){
this.age = age;
}
public String getName(){
return this.name;
}
public char getGender(){
return this.gender;
}
public int getAge(){
return this.age;
}
}
BusTicket.java
public class BusTicket {
private int ticketNo;
private float ticketPrice;
private float totalAmount;
Person person = new Person();
int age = person.getAge();
char g = person.getGender();
public void setTicketNo(int ticketNo){
this.ticketNo = ticketNo;
}
public void setTicketPrice(float ticketPrice){
this.ticketPrice = ticketPrice;
}
public void setTotalAmount(float totalAmount){
this.totalAmount = totalAmount;
}
public void calculateTotal()
{
if(age<16)
{
totalAmount = ticketPrice/2;
setTotalAmount(totalAmount);
}
else if(age>=60)
{
totalAmount = 3*(ticketPrice/4);
setTotalAmount(totalAmount);
}
else if(g == 'f'|| g== 'F')
{
totalAmount = 9*(ticketPrice/10);
setTotalAmount(totalAmount);
}
else{
setTotalAmount(ticketPrice);
}
}
public int getTicketNo(){
return this.ticketNo;
}
public float getTicketPrice(){
return this.ticketPrice;
}
public float getTotalAmount(){
return this.totalAmount;
}
}
TestMain.java
import java.util.Scanner;
public class TestMain {
public static BusTicket getTicketDetails()
{
Scanner sc = new Scanner(System.in);
BusTicket bt = new BusTicket();
System.out.println("Enter the ticket no:");
bt.setTicketNo(sc.nextInt());
System.out.println("Enter the ticket price:");
bt.setTicketPrice(sc.nextFloat());
return bt;
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
Person p = new Person();
BusTicket bt;
System.out.println("Enter the passenger name:");
p.setName(sc.nextLine());
System.out.println("Enter the gender(M or F/ m or f):");
p.setGender(sc.next().charAt(0));
System.out.println("Enter the age:");
p.setAge(sc.nextInt());
bt = getTicketDetails();
System.out.println("Ticket no:"+bt.getTicketNo());
System.out.println("Passenger Name:"+p.getName());
System.out.println("Price of a ticket : "+bt.getTicketPrice());
System.out.println("Total Amount : "+bt.getTotalAmount());
}
}
But my TotalAmount value is always coming 0.0, it is not getting updated.
And some test cases are failed please help to resolve them:
Fail 1 -
Incorrect access specifier/modifier for person -Should be a [private]
Fail 2 -
Check whether the signature(Returntype/Argument/AccessSpecifier/MethodName) of the method setPerson is correct
Fail 3-
Check whether the signature(Returntype/Argument/AccessSpecifier/MethodName) of the method getPerson is correct
Please Help
Thanks
You need to call calculateTotal to update totalAmount. Otherwise, it will be always 0.0.
...
System.out.println("Price of a ticket : "+bt.getTicketPrice());
bt.calculateTotal(); // Add this line
System.out.println("Total Amount : "+bt.getTotalAmount());
In your BusTicket class a new Person object is assigned to Person attribute and then you are trying to get age and gender details from that newly created Person object, but at this moment Person's age and gender are not populated yet.
Person person = new Person();
int age = person.getAge();
That's why you are getting 0. What should ideally happen is, you should pass the person object created using the input details to the BusTicket class and populate the BusTicket's person attribute with that person.For now I ll tell just that. :)
Give a try :)
In your BusTicket class, create a getter and setter for the Person object, and set the value from the main method.

Inputting data into an object

I'm doing a homework assignment, where we were asked to create a banking system. The first option is to create a customer and to store their information in a customer object. The start of my create_customer() method asks for their name and stores it into a newly create Customer object, but when i call the getName() method, nothing comes back. Here's the initial class Atm which holds all the actions for each option.
import java.util.ArrayList;
public class Atm
{
private ArrayList<Customer> cust;
private int starting_account_number;
private int starting_customer_number;
private String admin_pin;
private int interest_rate;
private int transaction_counter;
ConsoleReader console = new ConsoleReader(System.in);
public Atm() // constructor
{
cust = new ArrayList<>(100);
starting_account_number = 1001;
starting_customer_number = 101;
admin_pin = "abcd";
interest_rate = 5;
transaction_counter = 0;
}
void create_customer()
{
Customer customer = new Customer();
System.out.println("Please input your name: ");
customer.setName(console.readLine());
customer.getName();
while (customer.istrue)
{
System.out.println("Please input a 4 digit alphanumeric PIN: ");
customer.setPin(console.readLine());
if (customer.istrue == false) break;
}
System.out.println("A system generated ID was created for you, it is: ");
String customer_id = String.valueOf(starting_customer_number);
customer.setId(customer_id); // set customer ID
starting_customer_number++; //incrememnt customer ID
System.out.print(customer.getId());
cust.add(customer); //puts the customer object into atm class arraylist
}
Here's the customer class
import java.util.ArrayList;
public class Customer
{
public boolean istrue;
private String name;
private String id; // 3 digits string
private String pin; // 4 digits string
private ArrayList<Account> acct;
private double total_bal; // for all accounts
public Customer() //constructor
{
acct = new ArrayList<>(100);
istrue = true;
name = "NoName";
id = "000";
pin = "0000";
total_bal = 0;
}
// public cal_total_bal() { }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
if (pin.length() != 4)
{
System.out.println("That was not 4 digits, please input a 4 digit alphanumeric PIN: ");
}
else istrue = false;
}
You are calling a method
customer.getName();
But you are not actually doing anything with it.. you might want to print it:
System.out.println(customer.getName());

Deleting content and displaying all the content in JAVA

I'm here with my classes, my software is almost done after finishing last two things I will continue to GUI development. Anyway, here is my code:
public class Team
{
private String clubName;
private String preName;
private ArrayList<Branch> branches;
public Team(String clubName, String preName)
{
this.clubName = clubName;
this.preName = preName;
branches = new ArrayList<Branch>();
}
public Team() {
// TODO Auto-generated constructor stub
}
public String getClubName() { return clubName; }
public String getPreName() { return preName; }
public ArrayList<Branch> getBranches() { branches = new ArrayList<Branch>(branches);return branches; }
public void setClubName(String clubName) { this.clubName = clubName; }
public void setPreName(String preName) { this.preName = preName; }
public void setBranches(ArrayList<Branch> branches) { this.branches = new ArrayList<Branch>(branches); }
}
public class Branch
{
public ArrayList<Player> players = new ArrayList<Player>();
String brName;
public Branch() {}
public void setBr(String brName){this.brName = brName;}
public String getBr(){return brName;}
public ArrayList<Player> getPlayers() {players =new ArrayList<Player>(players); return players; }
public void setPlayers(ArrayList<Player> players) { this.players =new ArrayList<Player>(players); }
public String toString() {
return "Branches [" + brName + "]";}
}
public class Player
{
private String name;
private String pos;
private Integer salary;
private Integer number;
public Player(String name, String pos, Integer salary, Integer number)
{
this.name = name;
this.pos = pos;
this.salary = salary;
this.number = number;
}
public Player(){}
public String getName() { return name; }
public String getPos() { return pos; }
public Integer getSalary() { return salary; }
public Integer getNumber() { return number; }
public void setName(String name) { this.name = name; }
public void setPos(String pos) { this.pos = pos; }
public void setSalary(Integer salary) { this.salary = salary; }
public void setNumber(Integer number) { this.number = number; }
public String toString() {
return "Player [name=" + name + ", number=" + number + ", pos=" + pos
+ ", salary=" + salary + "]";
}
}
//TEST
String p1,p2;
int a1,a2;
String t, br;
System.out.print("Enter player name : ");
p1 = input.readLine();
System.out.print("Enter player position : ");
p2 = input.readLine();
System.out.print("Enter player salary : ");
a1 = Integer.parseInt(input.readLine());
System.out.print("Enter player number : ");
a2 = Integer.parseInt(input.readLine());
players[pCount].setName(p1);
players[pCount].setPos(p2);
players[pCount].setSalary(a1);
players[pCount].setNumber(a2);
ptmp.add(players[pCount]);
pCount++;
System.out.print("Enter the branch of player : ");
br = input.readLine();
int fff=0;
for(int i = 0; i<brCount;i++)
{
if(br.equals(myBranch[i].brName)==true){
myBranch[i].setPlayers(ptmp);fff=i;}
}
MY FIRST QUESTION : I'm trying to add a player to my system. When a player added I can easily add it to Branch class too and connect them. But I can't do it for Players' club. I mean I want to display which player plays in which club. But I can't do it.
MY SECOND QUESTION : Deleting a player is problem too. When I delete player it should be deleted everywhere. But couldn't figured that out.
In the test, you can see the display function I tried. It works fine for Branch-Player. And I wanna add Team connection too. Team-Branch-Player should be connected.
Q1: It depends how efficiently you want to do your searches.. for now, since you don't store back references you have to first search in which branch is your player and then search which is the club that contains your branch.
With good equals method for your Branch and Player class this is trivial:
for (Team t : teamList)
{
if (t.branches.contains(player))
return true;
}
return false;
But this won't be efficient since you'll have a O(n*m) complexity where n is the team size and m is the average branch size.
If you want something more efficient I'd suggest you to store backreferences inside your classes, you can have your Player class with two attributes
Branch currentBranch
Team currentTeam
and you can set them while you add the player to a branch/team.
Otherwise you can keep a separate HashMap that maps every player to his branch/team. Less memory efficient but quite straightforward.
Q2: to remove the Player from his branch/team you just have to know in which one he stays.. (using the answer to Q1), then before removing from players you just remove it from the corresponding branch/team:
Branch b = findWhichBranch(player);
Team t = findWhichTeam(player);
b.remove(player);
t.remove(player);
players[index] = null;
Of course if branch is implied by team you will just remove it from the branch, since there's no direct association between a player and a team.

Categories