Objects and attribute values [closed] - java

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.

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 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.

Converting Java code to model view controller architecture pattern [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 7 years ago.
Improve this question
I have written some code in java to give the some of the numbers 1 to 10 and then also display the average. I would like to change this to the model view controller method(thats what the tutor wants). We only had one lesson on it and i dont really understand how do change it. If someone could go through this and show me how(as if they were trying to teach a 5 year old) that would be great.
//JAVA CODE
public class Ex4 {
public static void main(String[] args) {
int sum = 0;
int average = 0;
for (int i=1; i < 10; i++){
sum = sum + i;
average = sum/i;
}
System.out.println("The sum is " + sum);
System.out.println("The average is " + average);
}
}
MVC is a basic pattern where you separate the model (data), view (display), and controller (logic) into different files and directories.
Here is an illustration of this model:
Here is an example of how that might look with your current code:
Controller Class (with main method included):
public class Ex4Controller {
//You could create a second controller,
//and put the main method there,
//then create a controller object.
public static void main(String[] args) {
//Initialize model
Ex4Model number = new Ex4Model(0,0.0);
//Execute business logic
Ex4Controller.getSumAndAverage(number);
//Set view
Ex4View.printSum(number.sum, number.average);
}
//Logic method
private static void getSumAndAverage(Ex4Model numbers){
for (int i=1; i < 10; i++){
//Here the controller interfaces with
//the model
numbers.sum = numbers.sum + i;
numbers.average = numbers.sum/i;
}
}
}
The controller class interfaces with both the model and the view. This class is where you do all the processes, and update the model or view. Any logic done, is going to be done in this class. If you wanted to get the mean of the numbers, you would write a method called getmean() in this class. Data manipulation is ONLY done here.
This is the Model class:
public class Ex4Model {
public int sum = 0;
public double average = 0;
//Custom constructor to set values
public Ex4Model(int sum, double average){
this.sum = sum;
this.average = average;
}
}
This class is used to hold the data. No logic is done here. This is a basic data structure that you use to house the data. This class does not interface with the view.
This is your view class:
public class Ex4View {
public static void printSum(int sum, double average){
System.out.println("The sum is " + sum);
System.out.println("The average is " + average);
}
}
This isn't a true view, but it's the best demonstration considering the circumstances. With Java, you would put your swing files here. The job of these files is to display the data. You'll notice that the controller passes all the data to this class, rather than accessing the data from the model.
This will output to the console:
The sum is 45
The average is 5.0
Something to keep in mind with MVC, is that you can have multiple controllers, models, and views. This is a very simple example. By using MVC, developers & programmers are able to better organize the data. They know where everything is being done, rather than having views manipulate data in some area's, and not in others.
I hope this makes sense.
As a (very) rough guideline:
Model: Stores the data. In this case, the sum and the average.
View: Displays the data. In this case, writing the data out with System.out. When the model changes, update the display (write the new values out).
Controller: Manipulates the data. In this case, taking an array of ints, computing sum and average, and giving the results to the model.
So overall, Controller computes sum & average, gives those values to Model. View is notified that Model changed. View displays Model's values.
Create 3 classes:
Let say Ex4Model, which just has 2 member variables in it called sum and average, and the corresponding get and set methods for each. This will hold your data.
We can then create the view, lets say Ex4View, which has a method say called render(Ex4Model model) which outputs the stuff you want from the model, in your case the sum and average.
Then you can create the controller, Ex4Controller, which has a method calculate(). Inside it it performs the calculations and feeds them to the model (in this simple example you can just create a new instance of it) and then calls render() on the view.
The rest is for you to join together, this is your homework.

java codes for a restaurant multiple steps [closed]

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

Java - Error in eclipse: the left hand side of an assignment must be a variable

This is a small part of my code. My project is to simulate a whole school system. To add teachers, courses etc. All of my class members are private, so i created setters and getters methods. I try to give to 'teachersNum' a value and this must be automatic(not from keyboard). So i want to give it value 1 if its the first teacher etc. I hope you can understand. Sorry for my English.
public void addTeachersList(Teachers teachers) {
if(this.teachersSize<100){
this.teachersList[this.teachersSize] = teachers;
this.teachersList[this.teachersSize].getTeacherNum() = this.teachersSize -1;
this.teachersSize++;
}
}
You'll have to call a setter:
this.teachersList[this.teachersSize].setTeacherNum(this.teachersSize-1);
Calling the getter getTeacherNum just gives you the number, it isn't a reference to that property.
Although I must say, you'd really do yourself a favor by using a List implementation instead of arrays.
In this line
this.teachersList[this.teachersSize].getTeacherNum() = this.teachersSize -1;
getTeacherNum() returns a value. You can't assign to it.
You have the problem here
this.teachersList[this.teachersSize].getTeacherNum() = this.teachersSize -1;
.getTeacherNum() will return a value which must be stored in a variable on left side.
eg:
temp = .getTeacherNum();
And its better to use a static variable to keep the count of teachers, so every time a teacher is created he/she gets a nos which is different from the previous one
eg:
xxxx001
xxxx002
xxxx003
You have the problem here
this.teachersList[this.teachersSize].getTeacherNum() = this.teachersSize -1;
.getTeacherNum() will return a value which must be stored in a variable on left side.
eg: temp = .getTeacherNum();
And its better to use a static variable to keep the count of teachers, so every time a teacher is created he/she gets a nos which is different from the previous one
eg:
xxxx001
xxxx002
xxxx003

Categories