java codes for a restaurant multiple steps [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Question 1:
Assuming “OOP Restaurant” owner has engaged you to write a Java
program to take the restaurant customer order. The beverage menu of
the restaurant is as shown in Table 1. This program must allow customer
to decide how many items he/she wish to order. Then, it will let the
customer to choose the each item according to his/her preference. Upon
completion of the ordering, the program will display the total amount of
the order to the customer. Then, the program must ask the customer
whether to do another set of ordering.
In your code, you must create a method to process the item choice and
return the price of the item using the following method signature:
double processItem(int input)
The sample out is as shown in Figure 1.
Beverage | Price
Fried Rice | RM5.50
Chicken Rice | RM5.00
Toast Bread | RM2.00
Mixed Rice | RM3.80
Table 1
How do i even start this? i'm a law student but got forced to do this please do help me out your kindness would be repayed thanks in advance

Having written the answer out this is quite a complex task for a non-programmer. There's concepts of how a program should be structured to contend with after which comes the compilation and running.
This answer is in just that order, first I'll explain what I think the key points are (sure I've missed some, as much of this is second nature) then I'll give you pointers on how to run the code.
Step 1.
Think about what's involved if you were going to do this on paper - you'd have a list of beverages each with a name and a price (the menu). An order comprises of one or more beverages from the menu in varying quantities. You multiple the price of each beverage by the quantity to get the cost of the order.
Step 2.
Modern computer languages use a technique call Object Orientation, which in a nutshell involves describing the entities in general terms to create what is known as classes. When presented with a problem, like that in step 1, a good rule of thumb in deciding what the classes should be is to look at the nouns - in this case beverage, menu and order look like good candidates. A class typically has attributes (the data that will make instances unique) and behaviour (operations based on that data) though you'd don't neccessarily have to have both as you can see from the code below.
Step 3.
I imagine to a non-programmer, step 2 doesn't make much sense, so here's some code (which I hope makes it a bit clearer):
/**
* This is the way classes are defined in Java, the public bit just says it's visible
* to every other class in the system.
*/
public class Beverage
{
//These are the attributes (fields) of the class. It's good practice to make them
//private so that they can only be accessed from within the class.
private String name;
private BigDecimal cost;
/**
* This is the constructor, which is used to create instances of the class. In
* this case it takes the arguments used to initialize the attributes of the class.
*/
public Beverage(String name, BigDecimal cost)
{
this.name = name;
this.cost = cost;
}
/**
* This is a getter, which provides access to the attributes from outside of the
* class.
*/
public BigDecimal getCost()
{
return this.cost;
}
public String getName()
{
return this.name;
}
}
public class Order
{
//This line is assigning an instance of HashMap (a standard data structure class
//in Java). A map is a bit like a dictionary, you have a key in this case the
//beverage that allows you to look-up another value, the quantity.
private Map<Beverage, Integer> beverages = new HashMap<Beverage, Integer>();
public BigDecimal getTotal()
{
BigDecimal total = BigDecimal.ZERO;
//Loop over all the beverages that have been added to the map summing the cost.
for (Beverage beverage : this.beverages.keySet())
{
//Convert the quantity in the map to a BigDecimal needed for the multiply method.
BigDecimal quantity = new BigDecimal(this.beverages.get(beverage));
total = total.add(beverage.getCost().multiple(quantity));
}
return total;
}
public void add(Beverage beverage, Integer quantity)
{
//Store the quantity against the beverage.
this.beverages.put(beverage, quantity);
}
}
These two classes are all you need to solve the problem. Menu is abscent because Java provides a class for a list of items. Next you need to use them in a program.
Step 4.
In Java any class can be 'run' providing it has a special method called main. Again, it's probably easier with an example:
public class Restaurant
{
/**
* The main method is static meaning it can be accessed without creating an instance
* of the Restaurant class.
*/
public static void main(String[] args)
{
Map<String, Beverage> menu = new HashMap<String, Beverage>();
//Create the instances of Beverage and add them to the menu.
menu.put("Fried Rice", new Beverage("Fried Rice", new BigDecimal(5.50)));
menu.put("Chicken Rice", new Beverage("Chicken Rice", new BigDecimal(5.00)));
menu.put("Toast Bread", new Beverage("Toast Bread", new BigDecimal(2.00)));
menu.put("Mixed Rice", new Beverage("Mixed Rice", new BigDecimal(3.80)));
//Create an order and add items from the menu to it.
Order order1 = new Order();
order1.add(menu.get("Fried Rice"), 2);
order1.add(menu.get("Toast Bread"), 3);
order1.add(menu.get("Mixed Rice"), 1);
System.out.println("Total for order 1: " + order1.getTotal());
//Create another order and add items from the menu to it.
Order order2 = new Order();
order2.add(menu.get("Chicken Rice"), 1);
order2.add(menu.get("Mixed Rice"), 1);
order2.add(menu.get("Toast Bread"), 2);
System.out.println("Total for order 2: " + order2.getTotal());
}
}
Step 5.
That's all the code I think you'll need. But in order to run it there's a few further steps. First is to install the Java Development Kit, which can be download from Oracle. Then, in Java, each class is typically declared in a text file that has the same name as the class with a .java extension - you'll end up with Beverage.java, Order.java and Restaurant.java. Next you need to compile your program - in basic terms this is the process of verifying the code you have written and converting it to something the Java Runtime can understand. I won't attempt to explain that, it's pretty well covered in the Getting Started Guide, which also explains how to run a Java program - ultimately you'll be looking for a command line that looks something like:
java -cp [path to class files] Restaurant

Related

Java constructor creates many null instances before the required object

this is my first question on here and I did a search before forming it, so I hope everything is as required.
I am working on a school assignment in Java. I am able to produce the required output but there are a lot of null instances created first. I don't understand why. Information about the library the professor created for the course and the code are below
Library included with this course: i2c.jar. It can be found here.
included in this Library are the classes Country and CountryDB. The API for the Country class can be found at http://130.63.94.24/~roumani/book/doc/i2c/ca/roumani/i2c/Country.html
The API for the CountryDB class can be found at http://130.63.94.24/~roumani/book/doc/i2c/ca/roumani/i2c/CountryDB.html
I am asked to create a class called Game, using the Country and CountryDB APIs.
The only attribute is db, which is an instance of CountryDB.
The constructor only sets the attribute (db) for this instance to a new CountryDB object.
The class is also meant to include a method (called qa) that follows this pseudocode:
get a reference to the database's capital city list
determine the size of this list. Cal it n.
generate a random number in [0,n) called index.
invoke get(index) on the list to get a random capital city. Call it c
get a reference to the database's data map
invoke get(c) on the map to get a reference to a country. Call it ref.
The method is then supposed to return one of two Strings (which will be clear in the code). Everything works as it should, except I get a lot of "nulls" before the desired output. When made into a List, db has size 241 so I suspect I am creating 241 null instances and 1 proper instance. I have no idea why though. I have tested every line of code in my method and the constructor was dictated by the textbook.
CODE
package ca.yorku.eecs.caps;
import java.util.List;
import java.util.Map;
import ca.roumani.i2c.Country;
import ca.roumani.i2c.CountryDB;
public class Game
{
private CountryDB db;
public Game()
{
this.db = new CountryDB();
}
public String qa()
{
List<String> capitals = db.getCapitals();
System.out.println(capitals.toString());
int n = capitals.size();
System.out.println(n);
int index = ((int) (n * Math.random()));
System.out.println(index);
String c = capitals.get(index);
System.out.println(c);
Map<String, Country> data = db.getData();
Country ref = data.get(c);
if (Math.random() > 0.5)
{
return "What is the capital of " + ref.getName() + "? \n" + ref.getCapital();
}
else
{
return ref.getCapital() + " is the capital of? \n" + ref.getName();
}
}
public static void main(String[] args)
{
Game g = new Game();
System.out.println(g.qa());
}
}
the System.out.println() statements are only there to test when the nulls occur. It clearly happens immediately because my psvm output is 241 nulls (on separate lines) followed by my desired output. Can somebody please tell me what I am doing wrong?
And, more generally (to help more people) how do you implement classes, the constructor of which instantiates another class and sets it as an attribute value?
I appreciate any help. Also, please note, I am not trying to get others to do my work for me. I've spent hours on this and my lab TA also wasn't sure why it happens either. He would have helped me correct it had he known how.
Thank you.

Java class: limit instance variable to one of several possible values, depending on other instance variables

I am sorry for the vague question. I am not sure what I'm looking for here.
I have a Java class, let's call it Bar. In that class is an instance variable, let's call it foo. foo is a String.
foo cannot just have any value. There is a long list of strings, and foo must be one of them.
Then, for each of those strings in the list I would like the possibility to set some extra conditions as to whether that specific foo can belong in that specific type of Bar (depending on other instance variables in that same Bar).
What approach should I take here? Obviously, I could put the list of strings in a static class somewhere and upon calling setFoo(String s) check whether s is in that list. But that would not allow me to check for extra conditions - or I would need to put all that logic for every value of foo in the same method, which would get ugly quickly.
Is the solution to make several hundred classes for every possible value of foo and insert in each the respective (often trivial) logic to determine what types of Bar it fits? That doesn't sound right either.
What approach should I take here?
Here's a more concrete example, to make it more clear what I am looking for. Say there is a Furniture class, with a variable material, which can be lots of things, anything from mahogany to plywood. But there is another variable, upholstery, and you can make furniture containing cotton of plywood but not oak; satin furniture of oak but not walnut; other types of fabric go well with any material; et cetera.
I wouldn't suggest creating multiple classes/templates for such a big use case. This is very opinion based but I'll take a shot at answering as best as I can.
In such a case where your options can be numerous and you want to keep a maintainable code base, the best solution is to separate the values and the logic. I recommend that you store your foo values in a database. At the same time, keep your client code as clean and small as possible. So that it doesn't need to filter through the data to figure out which data is valid. You want to minimize dependency to data in your code. Think of it this way: tomorrow you might need to add a new material to your material list. Do you want to modify all your code for that? Or do you want to just add it to your database and everything magically works? Obviously the latter is a better option. Here is an example on how to design such a system. Of course, this can vary based on your use case or variables but it is a good guideline. The basic rule of thumb is: your code should have as little dependency to data as possible.
Let's say you want to create a Bar which has to have a certain foo. In this case, I would create a database for BARS which contains all the possible Bars. Example:
ID NAME FOO
1 Door 1,4,10
I will also create a database FOOS which contains the details of each foo. For example:
ID NAME PROPERTY1 PROPERTY2 ...
1 Oak Brown Soft
When you create a Bar:
Bar door = new Bar(Bar.DOOR);
in the constructor you would go to the BARS table and query the foos. Then you would query the FOOS table and load all the material and assign them to the field inside your new object.
This way whenever you create a Bar the material can be changed and loaded from DB without changing any code. You can add as many types of Bar as you can and change material properties as you goo. Your client code however doesn't change much.
You might ask why do we create a database for FOOS and refer to it's ids in the BARS table? This way, you can modify the properties of each foo as much as you want. Also you can share foos between Bars and vice versa but you only need to change the db once. cross referencing becomes a breeze. I hope this example explains the idea clearly.
You say:
Is the solution to make several hundred classes for every possible
value of foo and insert in each the respective (often trivial) logic
to determine what types of Bar it fits? That doesn't sound right
either.
Why not have separate classes for each type of Foo? Unless you need to define new types of Foo without changing the code you can model them as plain Java classes. You can go with enums as well but it does not really give you any advantage since you still need to update the enum when adding a new type of Foo.
In any case here is type safe approach that guarantees compile time checking of your rules:
public static interface Material{}
public static interface Upholstery{}
public static class Oak implements Material{}
public static class Plywood implements Material{}
public static class Cotton implements Upholstery{}
public static class Satin implements Upholstery{}
public static class Furniture<M extends Material, U extends Upholstery>{
private M matrerial = null;
private U upholstery = null;
public Furniture(M matrerial, U upholstery){
this.matrerial = matrerial;
this.upholstery = upholstery;
}
public M getMatrerial() {
return matrerial;
}
public U getUpholstery() {
return upholstery;
}
}
public static Furniture<Plywood, Cotton> cottonFurnitureWithPlywood(Plywood plywood, Cotton cotton){
return new Furniture<>(plywood, cotton);
}
public static Furniture<Oak, Satin> satinFurnitureWithOak(Oak oak, Satin satin){
return new Furniture<>(oak, satin);
}
It depends on what you really want to achieve. Creating objects and passing them around will not magically solve your domain-specific problems.
If you cannot think of any real behavior to add to your objects (except the validation), then it might make more sense to just store your data and read them into memory whenever you want. Even treat rules as data.
Here is an example:
public class Furniture {
String name;
Material material;
Upholstery upholstery;
//getters, setters, other behavior
public Furniture(String name, Material m, Upholstery u) {
//Read rule files from memory or disk and do all the checks
//Do not instantiate if validation does not pass
this.name = name;
material = m;
upholstery = u;
}
}
To specify rules, you will then create three plain text files (e.g. using csv format). File 1 will contain valid values for material, file 2 will contain valid values for upholstery, and file 3 will have a matrix format like the following:
upholstery\material plywood mahogany oak
cotton 1 0 1
satin 0 1 0
to check if a material goes with an upholstery or not, just check the corresponding row and column.
Alternatively, if you have lots of data, you can opt for a database system along with an ORM. Rule tables then can be join tables and come with extra nice features a DBMS may provide (like easy checking for duplicate values). The validation table could look something like:
MaterialID UpholsteryID Compatability_Score
plywood cotton 1
oak satin 0
The advantage of using this approach is that you quickly get a working application and you can decide what to do as you add new behavior to your application. And even if it gets way more complex in the future (new rules, new data types, etc) you can use something like the repository pattern to keep your data and business logic decoupled.
Notes about Enums:
Although the solution suggested by #Igwe Kalu solves the specific case described in the question, it is not scalable. What if you want to find what material goes with a given upholstery (the reverse case)? You will need to create another enum which does not add anything meaningful to the program, or add complex logic to your application.
This is a more detailed description of the idea I threw out there in the comment:
Keep Furniture a POJO, i.e., just hold the data, no behavior or rules implemented in it.
Implement the rules in separate classes, something along the lines of:
interface FurnitureRule {
void validate(Furniture furniture) throws FurnitureRuleException;
}
class ValidMaterialRule implements FurnitureRule {
// this you can load in whatever way suitable in your architecture -
// from enums, DB, an XML file, a JSON file, or inject via Spring, etc.
private Set<String> validMaterialNames;
#Overload
void validate(Furniture furniture) throws FurnitureRuleException {
if (!validMaterialNames.contains(furniture.getMaterial()))
throws new FurnitureRuleException("Invalid material " + furniture.getMaterial());
}
}
class UpholsteryRule implements FurnitureRule {
// Again however suitable to implement/config this
private Map<String, Set<String>> validMaterialsPerUpholstery;
#Overload
void validate(Furniture furniture) throws FurnitureRuleException {
Set<String> validMaterialNames = validMaterialsPerUpholstery.get(furniture.getUpholstery();
if (validMaterialNames != null && !validMaterialNames.contains(furniture.getMaterial()))
throws new FurnitureRuleException("Invalid material " + furniture.getMaterial() + " for upholstery " + furniture.getUpholstery());
}
}
// and more complex rules if you need to
Then have some service along the lines of FurnitureManager. It's the "gatekeeper" for all Furniture creation/updates:
class FurnitureManager {
// configure these via e.g. Spring.
private List<FurnitureRule> rules;
public void updateFurniture(Furniture furniture) throws FurnitureRuleException {
rules.forEach(rule -> rule.validate(furniture))
// proceed to persist `furniture` in the database or whatever else you do with a valid piece of furniture.
}
}
material should be of type Enum.
public enum Material {
MAHOGANY,
TEAK,
OAK,
...
}
Furthermore you can have a validator for Furniture that contains the logic which types of Furniture make sense, and then call that validator in every method that can change the material or upholstery variable (typically only your setters).
public class Furniture {
private Material material;
private Upholstery upholstery; //Could also be String depending on your needs of course
public void setMaterial(Material material) {
if (FurnitureValidator.isValidCombination(material, this.upholstery)) {
this.material = material;
}
}
...
private static class FurnitureValidator {
private static boolean isValidCombination(Material material, Upholstery upholstery) {
switch(material) {
case MAHOGANY: return upholstery != Upholstery.COTTON;
break;
//and so on
}
}
}
}
We often are oblivious of the power inherent in enum types. The Java™ Tutorials clearly states "you should use enum types any time you need to represent a fixed set of constants."
How do you simply make the best of enum in resolving the challenge you presented? - Here goes:
public enum Material {
MAHOGANY( "satin", "velvet" ),
PLYWOOD( "leather" ),
// possibly many other materials and their matching fabrics...
OAK( "some other fabric - 0" ),
WALNUT( "some other fabric - 0", "some other fabric - 1" );
private final String[] listOfSuitingFabrics;
Material( String... fabrics ) {
this.listOfSuitingFabrics = fabrics;
}
String[] getListOfSuitingFabrics() {
return Arrays.copyOf( listOfSuitingFabrics );
}
public String toString() {
return name().substring( 0, 1 ) + name().substring( 1 );
}
}
Let's test it:
public class TestMaterial {
for ( Material material : Material.values() ) {
System.out.println( material.toString() + " go well with " + material.getListOfSuitingFabrics() );
}
}
Probably the approach I'd use (because it involves the least amount of code and it's reasonably fast) is to "flatten" the hierarchical logic into a one-dimensional Set of allowed value combinations. Then when setting one of the fields, validate that the proposed new combination is valid. I'd probably just use a Set of concatenated Strings for simplicity. For the example you give above, something like this:
class Furniture {
private String wood;
private String upholstery;
/**
* Set of all acceptable values, with each combination as a String.
* Example value: "plywood:cotton"
*/
private static final Set<String> allowed = new HashSet<>();
/**
* Load allowed values in initializer.
*
* TODO: load allowed values from DB or config file
* instead of hard-wiring.
*/
static {
allowed.add("plywood:cotton");
...
}
public void setWood(String wood) {
if (!allowed.contains(wood + ":" + this.upholstery)) {
throw new IllegalArgumentException("bad combination of materials!");
}
this.wood = wood;
}
public void setUpholstery(String upholstery) {
if (!allowed.contains(this.wood + ":" + upholstery)) {
throw new IllegalArgumentException("bad combination of materials!");
}
this.upholstery = upholstery;
}
public void setMaterials(String wood, String upholstery) {
if (!allowed.contains(wood + ":" + upholstery)) {
throw new IllegalArgumentException("bad combination of materials!");
}
this.wood = wood;
this.upholstery = upholstery;
}
// getters
...
}
The disadvantage of this approach compared to other answers is that there is no compile-time type checking. For example, if you try to set the wood to plywoo instead of plywood you won’t know about your error until runtime. In practice this disadvantage is negligible since presumably the options will be chosen by a user through a UI (or through some other means), so you won’t know what they are until runtime anyway. Plus the big advantage is that the code will never have to be changed so long as you’re willing to maintain a list of allowed combinations externally. As someone with 30 years of development experience, take my word for it that this approach is far more maintainable.
With the above code, you'll need to use setMaterials before using setWood or setUpholstery, since the other field will still be null and therefore not an allowed combination. You can initialize the class's fields with default materials to avoid this if you want.

Java Input as Variable Name [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to make a program to get information from a list, by entering a code. E.G:
'Enter the code:'
My input: d001
Then I want to print out information that belongs to this code. The information belongs to the String named 'd001', so in this case I want my input to be the name of the variable I am going to print out. How do I do this? Or is there a better solution to get information from a database list by entering the code name for it?
I could make a huge switch statement, but this is not efficient coding. I got this now:
public class Main {
public static Scanner idScanner = new Scanner(System.in);
public static int diseaseId = 0;
/** ID Scanning and reading: */
public static void executeId() {
diseaseId = idScanner.nextInt();
switch (diseaseId) {
case 001:
System.out.println(IdListener.d001);
break;
case 002:
System.out.println(IdListener.d002);
break;
case 003:
System.out.println(IdListener.d003);
break;
case 004:
System.out.println(IdListener.d004);
break;
case 005:
System.out.println(IdListener.d005);
break;
}
}
public static void main(String args[]) {
System.out.println(LayoutListener.titleString); /** Title String Display */
System.out.print(LayoutListener.idField); /** ID field Display */
executeId();
}
}
public class IdListener {
public static String d001 = "[Neuroblastomia]: Tumor that grows on the nerves of the spine.";
public static String d002 = "[Anorexia]: Mental disease to avoid eating and consuming.";
public static String d003 = "[TEMP3]: TEMP3.";
public static String d004 = "[TEMP4]: TEMP4.";
public static String d005 = "[TEMP5]: TEMP5.";
}
Using a Map may be a better solution to what you want to do.
Map<String, String> diseases = new HashMap<String, String>(); // Map<ID, Description>
diseases.put("d001", "[Neuroblastomia]: Tumor that grows on the nerves of the spine.");
diseases.put("d002", "[Anorexia]: Mental disease to avoid eating and consuming.");
// the rest of your diseases
So that when String disId = "d001" it will make things a lot simpler and you will not have a giant switch statement.
if(diseases.containsKey(disId))
System.out.println(diseases.get(disId));
else
System.out.println("That id does not exist!");
Use reflection
Field f= IdListener.class.getDeclaredField("d"+input);
f.get(null);
Very confusing question.
You mention databases but show no code or explanation for that.
Octal
One important flaw in your code: Do no use leading zeros on a numeric literal. The leading zero means the number should be interpreted as an octal number (base-8) rather than as a decimal (base-10).
So, case 001: should be case 1:.
Enum
If you have only a few of these disease codes, and they do not change during the runtime of your app, learn to use an enum. The enum facility in Java is much more powerful and flexible than in other languages.
Map
If the set of disease codes may change during runtime, and you have few enough of these to all fit comfortably into memory, then use a Map collection. A map tracks a bunch of objects ("keys") each of which is associated with another object (a "value"). Like a common dictionary book which tracks a bunch of words, and each word is assigned the text of a definition; each word is a key mapped to a value (it's definition).
In your case an Integer key (code number) maps to a String value (disease title/description). If you know a code number, you can ask the map to locate the matching disease title.
Database
If you have many of these diseases, too many to all fit into memory, use a database. For example the H2 Database.
Whenever you have a code number, query the database for the matching disease title.
You will need to learn about SQL and JDBC.

I have been tasked to create a foodstore that I can add and take food from, does my code achieve this?

I have been asked to model a foodstore that contains different types of food. I should be able to add a given quantity of a food type by using the addFood method and remove food using the takeFood method. The addFood must take the form addFood(String, int) and the takeFood must take the form takeFood(String), i.e. addFood("Steak", 5) would add 5 items of steak to the foodstore. I have attempted to make this class and wondered whether this meets what I have been tasked to do. For the sake of this example I will only use 2 food items but in reality there is much more.
public class Foodstore {
public void addFood(String food, int quantity) {
addFood("steak", quantity);
addFood("hay", quantity);
}
public void takeFood(String food) {
takeFood("Steak");
takeFood("hay");
}
}
Thanks in advance
Your food store is missing a warehouse
Map<String,Integer> warehouse = new HashMap<>();
and, as it is, when you add food you're ignoring the food you were told to add, not a good idea.
These are just some starting point, reorganize your code and explore your warehouse when you add data to make sure you're doing well.
I don't think so, you would need some kind of register where you actually save the information, like a Map:
Map<String,Integer> register = new HashMap<>();
You would have to rewrite your functions sth like this (have not been able to type it in an editor, but just so that you get the idea of it):
public void addFood(String food, int quantity) {
if (register.containsKey(food)) {
Integer newAmount = register.get(food) + quantity;
register.put(food,newAmount);
}
else {
register.put(food,quantity);
}
}
PS. You are (mis)using recursion, and I don't think it's what you want in your case. Your function addFood calls itself again and again without an end.

Objects and attribute values [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I need help with my homework. Please note that I have finished the code below myself, but am not sure if I am doing it correctly, especially the last sentence of my homework assignment.
My homework assignment:
Define a class called Building with the following properties. Every Building has a square footage (area) and stories. The constructor creates a Building with these two attributes. The methods get_squarefootage(), get_stories(), set_square_footage(), and set_stories() will be used to get and set the respective attribute values. The method get_info() will return all the current attribute values of the Building. Write a program that lets a user create Building objects and change their attribute values.
package building_hw2;
import java.util.Scanner;
public class Building {
int area;
int stories;
int get_squarefootage() { //get values of the area
return area;
}
int get_stories() { //get values of the stories
return stories;
}
void set_square_footage(int area) { //set values of the area
this.area = area;
}
void set_stories(int stories) { //set values of the stories
this.stories = stories;
}
void get_info() { //return all the current attribute balues of the building
System.out.println("The square footage of the building is " + area);
System.out.println("The building has " + stories + " stories");
}
//main method
public static void main(String[] args) {
Building Bldg = new Building(); //create a building object
Bldg.area = 40000;
Bldg.stories = 5;
Bldg.get_info(); //display the current values of the building
//get user input to create building object
Scanner keybd = new Scanner(System.in);
System.out.println("Please enter the square footage(area) of the building : ");
int bldgArea = keybd.nextInt();
System.out.println("Please enter the stories : ");
int bldgStories = keybd.nextInt();
Bldg.set_square_footage(bldgArea);
Bldg.set_stories(bldgStories);
Bldg.get_squarefootage();
Bldg.get_stories();
Bldg.get_info();
}
}
You seem to be doing it correctly. However I would like to point out a few things. First you should declare the member variables as private for better encapsulation of your class. You already have setter methods for changing the attribute value.
int area;
int stories;
In your main you can set building values as follows :
Bldg.set_square_footage_area(40000);
Bldg.set_stories(5);
The requirement for get_info is not very clear you should ask what exactly should be returned (some string representation of the attributes or just print current values of all attributes)
You're confusing "returning" and "printing to the console". The get_info() method should return something. It shouldn't print anything.
Fields should be private. Methods, in this case, should be public, since you want any other class to be able to call them. And you forgot to provide a constructor, althoughh your teacher asked you to provide one.
Please kindly inform your teacher that naming conventions exist in Java, and that teaching other conventions is not a good idea at all. A whole lot of frameworks and APIs assume the respect of the standard conventions. get_squarefootage() should be named getSquareFootage(). Same for the setter. Use real words, starting with a lowercase letter, for your variables: building, and not Bldg.
get_info should either return a String or be renamed to printBuildingAttributes.
You have Bldg.area, but why not have a setter method for this field? That would jive with your getter/setter paradigm. It looks like you already have it, so use it. Make the fields themselves private and only accessible thru your getter/setter methods.
If you are going to retrieve the number of stories or area of a building, you need to store it in a variable. Right now, you are retrieving it and throwing it away.
Also, get_info or get_area is not the right Java convention for method naming.

Categories