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.
Related
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.
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 8 years ago.
Improve this question
I have a HashMap of "buttons" which can be clicked with the key being the location (x and y coordinates) of the button. Every time new data is received from the database the buttons rearrange themselves and update their positions in the map and other values associated with the "button" object. Currently I have buttons as an immutable object so new buttons need to be created each time I receive new data.
When I thought of a real life example of this (buying a new, different colour version of your house instead of painting the one you already have) it seemed a bit wasteful to keep creating objects instead of just reusing the old ones, is this the best way to do it?
Creating new objects usually means allocating new memory, an operation that is quite expensive and something which should be avoided if a function really needs to be optimized.
It's hard (if not impossible) to say if it will be faster to create new objects or not in your specific case without any code. If we're talking about a list of 10 buttons it wont matter, but if we're talking about a list of trillions on buttons, you should probably try to reassign their values instead.
Below is a small example that illustrates the difference between creating new objects and reassigning a single value of an instance, if I understood you question correctly it should be somewhat similar to your case. The output on my machine can be seen below.
package org.stackoverflow;
import java.util.ArrayList;
public class Example {
public static class MyObject {
private double value;
public MyObject(double value) {
this.setValue(value);
}
public final void setValue(double value) {
this.value = value;
}
public double getValue() {
return this.value;
}
}
public static void main(String[] args) {
long start = 0;
ArrayList<MyObject> objects = new ArrayList<MyObject>();
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; ++i) {
objects.add(new MyObject(Math.random()));
}
System.out.println("Time to create 1.000.000 objects: "
+ Long.toString(System.currentTimeMillis() - start)
+ " ms.");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; ++i) {
objects.get(i).setValue(Math.random());
}
System.out.println("Time to reassign 1.000.000 objects: "
+ Long.toString(System.currentTimeMillis() - start)
+ " ms.");
}
}
Output
Time to create 1.000.000 objects: 323 ms.
Time to reassign 1.000.000 objects: 31 ms.
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.
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
I'm in a beginner's java class. This Lab is for me to make a class "Wallet" that manipulates an array that represents a Wallet. Wallet contains the "contents[]" array to store integers represing paper currency. The variable "count" holds the number of banknotes in a wallet. After writing methods (that match provided method calls in a serpate Driver class) to initialize the Wallet and add currency/update "count", I need to transfer the array of one instantiated Wallet to another. I don't know how that would work because the one Wallet class has only been messing with a wallet called "myWallet" and now I need to take a new Wallet called "yourWallet" and fill it with "myWallet"'s array values.
//I should note that using the Java API library is not allowed in for this course
My Wallet class looks like this so far:
public class Wallet
{
// max possible # of banknotes in a wallet
private static final int MAX = 10;
private int contents[];
private int count; // count # of banknotes stored in contents[]
public Wallet()
{
contents = new int[MAX];
count = 0;
}
/** Adds a banknote to the end of a wallet. */
public void addBanknote(int banknoteType)
{
contents[count] = banknoteType;
count = count + 1;
}
/**
* Transfers the contents of one wallet to the end of another. Empties the donor wallet.
*/
public void transfer(Wallet donor)
{
//my code belongs here
}
...
The Driver code looks like this:
public class Driver
{
public static void main(String args[])
{
Wallet myWallet = new Wallet();
myWallet.addBanknote(5);
myWallet.addBanknote(50);
myWallet.addBanknote(10);
myWallet.addBanknote(5);
System.out.println("myWallet contains: " + myWallet.toString());
// transfer all the banknotes from myWallet to yourWallet
Wallet yourWallet = new Wallet();
yourWallet.addBanknote(1);
yourWallet.transfer(myWallet);
System.out.println("\nnow myWallet contains: "
+ myWallet.toString());
System.out.println("yourWallet contains: "
+ yourWallet.toString());
I want to use addBanknote() to help with this, but I don't know how to tell the transfer() method to transfer all of myWallet into yourWallet.
I had the idea to do somethign like this in transfer():
yourWallet.addBanknote(myWallet.contents[i]);
with a traversal to increase i for myWallet contents. It seems horribly wrong, but I'm at a complete loss as to write this method.
If my problem is so unclear that nobody can help, I would be more than happy to receive advice on how to ask a better question or on how to search with correct terms.
Thanks for any help you can provide.
I don't want to spoil your homework as you seem to be going the right way, but I do have some comments which you may either take or not :)
First, I would probably put the bank note types in some enumeration. But as that sounds a bit to advanced, consider
public class Wallet {
public static final int ONE_DOLLAR_BILL = 1;
public static final int FIVE_DOLLAR_BILL = 5;
...
// looks a bit more readable to me
myWallet.addBanknote(ONE_DOLLAR_BILL);
Transferring all the banknotes from the donor to yourself should not be so much of a problem
(a for loop would do) but I think you're in a world of hurt if you are trying to implement a
removeBanknote(int banknoteType);
as you are using count not only as a length but also as an index variable. By this I mean that you assume contents[0] ... contents[count-1] hold valid banknotes. And how do you remove one without too much work?
Warning: a bit more advanced
In your case I would probably opt to have a banknoteType of 0 indicating an empty banknote slot in your wallet, and implement _addBanknote(int banknoteType) as:
public void addBanknote(int banknoteType) {
for (int i=0; i < contents.length; i++) {
if (contents[i] == 0) {
contents[i] = banknoteType;
count++;
return; // OK inserted banknote at the first empty slot
}
}
throw new RuntimeException("Wallet is full");
}
This may be a bit overwhelming at this point. But it would allow you to implement:
public void removeBanknote(int banknoteType) {
for (int i=0; i < contents.length; i++) {
if (contents[i] == banknoteType) {
contents[i] = 0; // better: NO_BANKNOTE = 0
count--;
return;
}
}
throw new RuntimeException("This wallet does not contain a banknote of type " + banknoteType);
}
Please note that in both methods I return when I successfully removed or added the banknote. Only when I could not find a free slot, or the requested banknote, I finish the for loop and end up throwing an exception and thereby stopping the program.
I think the question is fine and I think you're on the right path. The way you're calling Wallet#addBanknote(int) is correct. What you have said is the right thing:
public void transfer(Wallet donor)
{
// Traverse the donor's wallet
// Add the bank note from the donor to this wallet
// What do you think also needs to happen to make sure
// the donor is actually giving their bank note?
}
Just another thing, what would happen in your Wallet#addBanknote(int) method if you have more contents than the MAX?
You can create either a constructor that takes another wallet, or a function (as already mentioned) and use System.arraycopy to copy the array in one fell swoop. System.arraycopy is fast, and its definitely overkill for something small like this, but its good tool to have in your toolkit.
The other alternative mentioned, copy the elements from one array to the other element by element in a loop will work fine too.
The myWallet inside the transfer method is named 'donor', and with that, it doesn't look horribly wrong:
addBanknote (donor.contents [i]);
You just need a loop around it, and to remove the yourWallet. which is the name of an instance of that class. That instance is inside the Class/method this, but needn't be specified, because there is no other addBanknote-Method in scope, which could be meant. (Thanks to mangoDrunk).