class method to ask for userinput - java

I am really pretty new to java and have a homework assignment due in a couple days. Unfortunately when my teacher try's to help me out I just still don't understand it. I need to create two classes to compute a discounted loan and then a main class to call them all and actually make it work. This is my first class its all correct based on what the teacher wants.
package Project2;
public class Loan {
public double money;
public double interest;
public double loanperiod;
public double totaldiscount;
public Loan(){
money=0;
interest=0;
loanperiod=0;
}
//set money,interest,and loanperiod
public void setmoney(double newmoney){
money=newmoney;
}
public void setinterest(double newinterest){
interest=newinterest;
}
public void setloanperiod(double newloanperiod){
loanperiod=newloanperiod;
}
//get money,interest,and loanperiod
public double getmoney(){
return money;
}
public double getinterest(){
return interest;
}
public double getloanperiod(){
return loanperiod;
}
public double gettotaldiscount(){
return totaldiscount;
}
}
The second class I need to create another object. Then I have to create a method to compute the discounted loan and a method to describe the program, a method to get userinputs and a method calling the correct method from from the loan class above to display the output.
So far this is what I have for the second class, just a description method. But I am really confused as to how I am going to make a method to compute the discountedloan (I have the formula), and how to create a method to get userinputs. If I could get any help at all I would appreciate it. But please explain I really want to learn this rather then copy.
package Project2;
public class DiscountedLoan {
public DiscountedLoan(){
}
public void description(){
System.out.println("This program computes the proceeds of a discounted loan. Loan amount is in dollars and cents, Annual interest rate is in percentage, and the loan period is in number of years.");
}
}

There are a couple of object oriented principles you need to understand. The first is the idea of what a class is. A class is a thing. You have the definition, or the actual code, that represents the 'design' of the thing. It does stuff (methods) and has state (variables). An instance of a class is an actual implementation.
You can apply this principle to the real world easliy. For example, a car has a design somewhere. Engineers create models, CAD drawings etc and that is comparable to the coded class. At some point that design is turned into an actual car that is comparable to an instance of a class when your program runs.
In your code you have created a class definition for loan. It is just the design for what a loan looks like but doesn't actually contain any loan data. So when your program runs you need to create an instance of that loan to represent an actual loan. You can then use the methods of that class to populate the details, i.e. money, interest, etc.
When writing a method you need to decide a couple of things. What data does my method need to do its work and what data will it give back to me. In this case you may want to write a method that takes in a loan and returns a number to represent the discount. Your other method really just needs to display the user interface and call the appropriate methods with the right data.

This will allow you to read in integers that a user enters.
public int getLoanFromUserInput(){
try{
Scanner reader = new Scanner(System.in);
System.out.println("Enter a loan balance: ");
int n = reader.nextInt();
}catch(TypeMismatchException e){
System.out.println("Please enter a valid integer");
}
}

Related

Java - What is this asking me to do?

It's as follows:
I highlighted the part that I don't understand. What exactly does it mean when it's asking me to make those methods accept only two parameters? It seems like you would need 3, which are the test scores for each respective test?
The code I have so far:
public class Student {
private String ID;
private double test1;
private double test2;
private double test3;
private double average;
public Student(String sID, double sTest1, double sTest2, double sTest3, double sAverage)
{
ID = sID;
test1 = sTest1;
test2 = sTest2;
test3 = sTest3;
average = sAverage;
}
public Student(String sID)
{
ID = sID;
}
public void setTestScore(double sTest1, double sTest2, double sTest3)
{
}
public void getTestScore(double sTest1, double sTest2, double sTest3)
{
}
public double calcAverage()
{
average = (test1 + test2 + test3) / 3;
return average;
}
public void displayInfo(String ID, double test1, double test2, double test3, double average)
{
System.out.println("Student ID: " + ID);
System.out.println("Test 1 Score: " + test1);
System.out.println("Test 2 Score: " + test2);
System.out.println("Test 3 Score: " + test3);
System.out.println("Average test score: " + average);
}
}
Any insight as to what it's expecting me to do with the getTestScore and setTestScore methods would be appreciated.
Edit: Looks like the solution is to just use an array to store the values? I thought that would defeat the purpose of structuring it this way but it seems like as a beginner my options are a bit limited.
What exactly does it mean when it's asking me to make those methods accept only two parameters? It seems like you would need 3, which are the test scores for each respective test?
That would be one way to do it, but they want to do it slightly differently.
They want to have a method that sets the score only for a single test.
That is probably better as it
can be adapted easily to a greater number of tests
allows to set the scores one-by-one (as you may not even know the other scores yet).
So the "extra" parameter specifies which test you are talking about here.
To set all three scores, you would call this method three times (with different parameters).
Setter should have 2 parameters: test number and score
public void setTestScore(int testNo, double score) {
//YOUR HOMEWORK
}
Getter should return the score for the test number
public double getTestScore(int testNo) {
return YOUR_HOMEWORK;
}
Your Assignment in this case is to think of a good data structure to hold the results of a number of tests (currently three) and to retrieve them at a later time.
Hint: as others here have already suggested, you might think of a datastructure to map key values (your test number) to values (your score). The most basic of these structures being an array where the index is your key (watch out: zero-based!) and score is the value at that index...
With Arrays
You could still have some way of initialization to specify how many tests there are to be. Lets for a moment think of double[] scores = new double[3]; as a member variable in your class. Setting the 3rd test to score would be as simple as scores[2] = score;. Getting the result of the first test simply is scores[0];
The set method shouldn't accept all 3 scores at once. It should accept a single score parameter and a second parameter (int whose value is between 1 to 3) to indicate which test score should be updated.
Similarly the get method should accept the test number (between 1 and 3) and return the corresponding score.
The first method should add a test and a score to a Collection, let's say a HashMap<Integer, Double>. Like this:
public void addScore(int testId, double score) {
myTestsMap.put(testId, score);
}
The second part should retrieve the score from the map, like this:
public double getScoreForTest(int testId) {
if(myTestsMap.containsKey(testId){
return myTestsMap.get(testId);
} else {
return -1;
}
}
myTestsMap should be a class field so it's state is kept. Create it in the constructor like that:
myTestsMap = new HashMap<Integer, Double>;
As for a theoretical background:
the two methods are so-called getter and setter. It is a good practice to keep your class fields private and only allow access through such methods. It allows you to analyze the in-coming and out-going data, among other things.
Map is a data structure which maps a set of unique keys to non-unique values. HashMap is one of Map's implementations.
Another option not mentioned here is to hold your test scores in an ArrayList:
public class Student {
private String ID;
private ArrayList<Double> testScores = new ArrayList<>();
//CONSTRUCTOR
public void setTestScore(int testNumber, double score) {
//YOUR HOMEWORK
}
public double getTestScore(int testNumber) {
//YOUR HOMEWORK
}
Now you can add your test scores and they can be positional based on the index in the list. Note that ArrayList is also 0-based, so you'll have to correct for that. This approach also gives you the added benefit of being able iterate through test scores and print them out in the correct order.
The student object should have a Map<Integer, Double> field that stores the test number as the key and the score they got on that test as the value. The set method will put(testNumber, score) and the get method will return the test score by get(testNumber);
What seems confusing perhaps is the requirement to provide a constructor that sets all fields? Perhaps you expect the constructor method signature to look just like the setTestScore method?
If you're still in need of help, try to think a second about what the lesson is about. Are you learning about collections?
What exactly does it mean when it's asking me to make those methods accept only two parameters? It seems like you would need 3, which are the test scores for each respective test?
Try thinking about what the method is supposed to do, rather than how you would go about doing it.
The name of the method is a giveaway - setTestScore.
That would indicate to me, that I want to set the score for a single test.
Now, I would ask myself, what information would I need to change the score for a single test?
I would need something that identifies an individual test. E.g the integer 0 for test 1, integer 1 for test 2 etc.
I would also need the actual test score, so that I can store it.
Now I know that I likely need two parameters, one for the test identifier, and one for the test score.
So now, I need a way to store the test score in a specific place using the identifier.
Given that I have an identifier which is an integer, it should hopefully be clear that I would want to use an array.
The reason I would choose an array is because it accepts an integer, and allows me to access the data at that place in the array.
A section of pseudocode to highlight what I have proposed above:
setTestScore ( parameter1 testIdentifier, parameter2 testScore )
ArrayOfTestScores[testIdentifier] = testScore
Note regarding your second question
It seems like you would need 3, which are the test scores for each
respective test?
If someone sent you the following information in an email,
and asked you to store/update the value for a student's test in an excel sheet:
no value
65.7
no value
Sure, you can see right away you need to update the student's second test.
But, is there a better way?
How about the person just sends me the test number and the score?
Test 2: 65.7
Seems to be easier, because I have an actual identifier for the test to be updated.
And I also don't need redundant information in the email.
When starting off with programming it can help to try and turn the problem into a real life example which you can hopefully relate to. It could help you understand what makes sense and what doesn't. Eventually, as problems get trickier, you will likely need to learn some formal approaches to problem solving. But for this example, making a simple real life equivalent of what you're doing can help.
Ideally you would want to have everything object oriented, that would mean that the Test themselves would be their own class.
I think what is expected is that the first value is the number of the test (1 through 3) and the second value is the actual value. So the method signature that you have is wrong. It should just have two paramters. The first being the number and the second being the score.
What happens after the setter is called?
Well... you have to decide on some structure to store that data. It is basically three pairs of data. Like I mentioned before, it would be nice to have a Test class, but a simple data structure should suffice. I will give you a hint about the data structure : it should be key/value based. The key is the id of the Test, and the value is the value of the test. Have a read about java collections to see if there is any kind of data structure that can help you with this.
I think you are supposed to create a Map of some kind, with the test ID as a key, and the score as a value.
Your setter would populate the map with the score for the current test ID.
Your getter would retrieve the score in the map, corresponding to the asked test ID.
What exactly does it mean when it's asking me to make those methods
accept only two parameters? It seems like you would need 3, which are
the test scores for each respective test?
the method should accept test-id and test-score, and set data to proper attribute,
public void setTestScore(int testNumber, double testScore)
{
if(testNumber == 1)
test1=testScore;
else if(testNumber == 2)
test2=testScore;
else if(testNumber == 3)
test3=testScore;
}
and get method should take 1 param (testNumber)
public double getTestScore(int testNumber){
if(testNumber == 1)
return test1;
else if(testNumber == 2)
return test2;
else if(testNumber == 3)
return test3;
}

Is this proper encapsulation for this Java code? I am confused

Does this Java code involving a Book class use proper encapsulation? I feel it can be a lot simpler if I omit some methods but we're required to every method that is in there [especially setters and getters].
Here's the first class:
public class Book
{
private String title;
private double price;
private final double SALES_TAX=0.075;
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title=title;
}
public double getPrice()
{
return price;
}
public void setPrice(double price)
{
this.price=price;
}
public double getSalesTax()
{
return SALES_TAX;
}
public double increasePrice(double incresePrice)
{
return incresePrice;
}
public double calculateSales(double sales)
{
return sales;
}
}
And the second class:
public class BookDriver
{
public static void main(String[] args)
{
Scanner keyboard=new Scanner(System.in);
Book bookOne=new Book();
Book bookTwo=new Book();
bookOne.setTitle("Life of Pi");
System.out.print("Enter number to buy of "+bookOne.getTitle()+": ");
bookOne.setPrice(13.50*bookOne.calculateSales(keyboard.nextDouble()));
bookOne.setPrice((bookOne.getPrice()*bookOne.getSalesTax())+bookOne.getPrice());
System.out.print("Cost for "+bookOne.getTitle()+" $");
System.out.printf("%.2f"+"\n",bookOne.getPrice());
bookTwo.setTitle("Harry Potter: The Goblet Of Fire");
System.out.print("Enter number to buy of "+bookTwo.getTitle()+": ");
bookTwo.setPrice(22.00*bookTwo.calculateSales(keyboard.nextDouble()));
bookTwo.setPrice((bookTwo.getPrice()*bookTwo.getSalesTax())+bookTwo.getPrice());
System.out.print("Cost for "+bookTwo.getTitle()+" $");
System.out.printf("%.2f"+"\n",bookTwo.getPrice());
System.out.print("Enter percent increase of "+bookOne.getTitle()+": ");
bookOne.setPrice((bookOne.getPrice()*bookOne.increasePrice(keyboard.nextDouble()))+bookOne.getPrice());
System.out.printf("Cost of "+bookOne.getTitle()+": $"+"%.2f"+"\n",bookOne.getPrice());
System.out.print("Enter percent increase of "+bookTwo.getTitle()+": ");
bookTwo.setPrice((bookTwo.getPrice()*bookTwo.increasePrice(keyboard.nextDouble()))+bookTwo.getPrice());
System.out.printf("Cost of "+bookTwo.getTitle()+": $"+"%.2f"+"\n",bookTwo.getPrice());
keyboard.close();
}
}
I know that this is a lot so I'm not really expecting much in terms of a response but anything would help. Thanks!!
Let's look at the point of encapsulation. You have a Class which consists of properties and methods. The idea behind encapsulation is, you want the methods in your class to be the only way to change the value (state) of the properties. Think of it like this: if some other code in the program wants to change the value of one of the properties, it cannot do it itself, it must ask a method on the class they reside in to do it. That way, you control access to the properties.
The way this is implemented is with getter and setter methods of which you have created a few. A getter method returns the value of the property and a setter method changes it to a new value.
1.
Your getter and setter methods up to increasePrice() are good. You are preventing access to the properties other than from the methods on your class.
2.
increasePrice() only spits out what was passed into it. It doesn't change the value of any of the properties and thus has no purpose. If you want to be able to increase the price you can change the method like so:
public void increasePrice(double amountOfPriceIncrease) {
price += amountOfPriceIncrease;
/*
price += amountOfPriceIncrease is the same as
price = price + amountOfPriceIncrease
*/
}
3.
This line is a bit troubling. For starters, increasePrice() doesn't do anything other than spit out what was put into it and secondly, there is a lot going on in the one line that makes it complicated and hard to follow.
bookTwo.setPrice((bookTwo.getPrice()*bookTwo.increasePrice(keyboard.nextDouble()))+bookTwo.getPrice());
You dont necessarily need all the setters. For example, its probably reasonable to assume that a book has a title, and it doesnt change. So you can make it final, omit the setter, and pass it into the constructor.
Also, think about how you're modelling things. Is sales tax a property of a book? I'd say not.
Because all the required variables title, price for class Book are set to private, and that access can only be used using get..(), and changing it if possible can only be used using set..(some variable) or an instance method affecting one of the fields, it demonstrates proper encapsulation, so all getting and setting are regulated.
However, I spotted several mistakes in BookDriver, namely with the improper usage of Book fields.
The price should change only through setPrice or increasePrice.
You should also implement getPriceAfterTax to determine after-tax prices for a book.
The total cost of the books you bought should not involve any setPrice.
There is a mistake with public double calculateSales(double sales). It does nothing but returns back sales. The calculateSales should calculate the total cost of the book(s) being bought, using one int variable, and you also resorted in changing the price of these books, which shouldn't happen. It is the reason why you wrote messy code, as in the excerpt
bookTwo.setPrice(22.00*bookTwo.calculateSales(keyboard.nextDouble()));
bookTwo.setPrice((bookTwo.getPrice()*bookTwo.getSalesTax())+bookTwo.getPrice());
This avoids the potential case of changing the values of that BOOK object to unexpected or unusual values and value combinations.
Additionally, SALES_TAX can be made into a public static final double instead, as it is assumed to never change, and you can simply obtain SALE_TAX without requiring getSalesTax().
The last two methods do not make much sense. You simply return what you put in. Do it this way:
public double increasePrice(double increase)
{
price *= increase;
}
public double calculateSales(double sales)
{
//return {your formula}
}

Trouble running methods on objects of a polymorphic array in Java

I was given 2 classes for the assignment: Sale and DiscountSale (which extends Sale). I'm supposed to create a new class called MultiItemSale which will create an array (shopping cart) of both Sale and DiscountSale objects. But I can't get methods from DiscountSale to work on DiscountSale ojbects within the array.
class Sale (the base class) has some methods, setName() and setPrice() in particular.
class DiscountSale extends Sale, so it can use setName() and setPrice(), but it also has setDiscount() among other things.
in MultiItemSale:
Sale[] shoppingCart = new Sale[numOfItems];
From my understanding, since DiscountSale extends Sale, both Sale and Discount Sale objects should be able to placed within this array, correct?
I use a for loop to ask if an item is discounted. If it isn't then:
shoppingCart[i] = new Sale();
if it is discounted:
shoppingCart[i] = new DiscountSale();
And this is where I begin to run into issues:
The following works, because setName() and setPrice() are from the Sale class
Also, this is all under an if-statement that says if item is discounted, then:
shoppingCart[i] = new DiscountSale();
shoppingCart[i].setName(name);
shoppingCart[i].setPrice(price);
But if I try to do this I get errors because setDiscount() is from DiscountSale:
shoppingCart[i].setDiscount(discount);
Eclipse tells me, "The method setDiscount(double) is undefined for the type Sale". If
shoppingCart[i] = new DiscountSale();
why can't I use a method from DiscountSale on that object? I think I have a misunderstanding of how polymorphism and arrays work.
All the compiler knows is that you have Sales, so those are the only methods you can use. Polymorphism is for the situation when you have the same function calls on different kinds of objects and the same function call will behave differently depending on what kind of object it is.
In this example, name, price, and discount could be parameters of your constructor. That way you could pass them when you say new, and you wouldn't have to call a setting method afterwards.
Edit: Looking at the Wikipedia article on the Circle-Ellipse Problem, it occurs to me that any Sale has an implicit discount of 0%. You could use only DiscountSales and be able to access all their members, perhaps including a flag indicating whether the discount can be changed.
In the parlance of object-oriented design, a DiscountSale is a Sale.
Normally, a program would collect Sale and DiscoutSale objects into the same Sale collection in order to perform common Sale processing on those objects in the collection defined by the Sale API. So it doesn't make a lot of sense that you would try to use a statement like:
Sale[] shoppingCart = new Sale[] { ... };
:
:
shoppingCart[i].setDiscount(...);
Because a Sale isn't a DiscountSale, setting a discount rate on a top level Sale item, as you've designed it, isn't part of its API and the statement doesn't make a lot of sense.
DiscountSale objects will inherit the methods from Sale (a DiscountSale is a Sale), but Sale objects will have no knowledge of any subclass-specific methods defined in DiscountSale (a Sale object doesn't have to be a DiscountSale).
So what to do?
A common solution to a problem like this is to take advantage of polymorphism. For example, in your Sale class make a method such as getNetPrice() part of its API.
public class Sale {
protected double price;
:
:
public double getPrice() { return price; } // return original price
public double getNetPrice() { return price; } // return discounted price
:
:
}
Notice that the two methods in Sale are identical. How come? Because their contracts are different. The first returns the original price. The second is specified to return the discounted price. Because Sale objects have no discount, it simply returns the original price as well.
However, the DiscountSale class would take advantage of polymorphism to fulfill the API contract:
public class DiscountSale extends Sale {
private double discountRate; // specified as percent off (0.0 to 1.0)
:
:
#Override
public double getNetPrice() {
return (super.price - (super.price * discountRate));
}
:
:
}
Here, DiscountSale objects are defined so that the discount rate is set at the time the object is created. This is pretty straightforward since, as we've said, setting a discount rate on Sale objects in the collection (which may or may not be discounted) is more confusing.
The DiscountSale uses the Sale contract and overrides the getNetPrice() method to calculate and return the discounted price. In this way, both objects can be in the same collection and share a common API to get at the nondiscounted or discounted prices.

Understanding classes and variables in java [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 9 years ago.
Improve this question
I am new to Java and this was a example I found in the book I am reading.There are several things I do not understand in this code.Please help me to understand it.
/*
* CalculatorModel
* Encapsilates the data model used by the calculator Application
*/
public class CalculatorModel{
private double operand1;
private double operand2;
public void setOperand1(double value){
operand1=value;
}
public void setOperand2(double value){
operand2=value;
}
public double getOperand1(){
return operand1;
}
public double getOperand2(){
return operand2;
}
public String toString(){
String s = "operand 1=" + operand1 + "operand 2=" + operand2;
return s;
}
}
/*
* CalculatorHelper
* A class that performs mathematical functions for a calculator program
*/
public class CalculatorHelper{
private CalculatorModel calcModel;
public CalculatorHelper(){
calcModel=new CalculatorModel();
}
public void setOperand1(double value){
calcModel.setOperand1(value);
}
public void setOperand2(double value){
calcModel.setOperand2(value);
}
public double add(){
return calcModel.getOperand1()+calcModel.getOperand2();
}
public double subtract(){
return calcModel.getOperand1()-calcModel.getOperand2();
}
public double multiply(){
return calcModel.getOperand1()*calcModel.getOperand2();
}
public double divide(){
return calcModel.getOperand1()/calcModel.getOperand2();
}
}
Please help me to understand what is done by
private CalculatorModel calcModel;
public CalculatorHelper(){
calcModel=new CalculatorModel();
}
in the calculatorHelper class. Is calcModel a variable a variable of type CalculatorModel? What is the difference of having a object as a data type than a primitive data type to a variable?
If calcModel is a variable what is done by the line calcModel=new CalculatorModel();
I don't understand why it is important to have two classes as CalculatorModel and CalculatorHelper.
What is done with the method
public void setOperand1(double value){
calcModel.setOperand1(value);
}
in the helper class as there's already a setmethod in CalculatorModel class.
This is what I tried and what's wrong with this code?
public class Calculator{
private double num1,num2;
public void setValue1(double value1){
num1=value1;
}
public void setValue2(double value2){
num2=value2;
}
public double getValue1(){
return num1;
}
public double getValue2(){
return num2;
}
public double add(){
return getValue1()+getValue2();
}
public double subtract(){
return getValue1()-getValue2();
}
public double multiply(){
return getValue1()*getValue2();
}
public double divide(){
return getValue1()/getValue2();
}
}
"What is the difference of having a object as a data type than a primitive data type to a variable?"
Programming is all about data. Classes you can consider as complex data, and primitives as simple data. Say you have a class School
public class School {
}
What does school have? It has students. You can't represent a student with an of primitive types, because it just doesn't make sense for a student to be a double, int boolean, etc. So a student is another complex data type, like a school. So in order for the student to be represented as data contained by the school, you need a Student class also, which can hold the student's name, address and such
public class Student{
String firstName;
String lastName;
String address;
int age;
So to fully represent the student being in the school you use the has-a relationship, where School has-a Student
public class School {
Student student;
}
To delve even deeper, does a school only have one student? No, it should have many students. So you would represent that as a School having an array of Students
public class School {
Student[] students;
}
So in terms of data, you have a data tree like this now
School
Student
firstName
lastName
address
age
Student
firstName
lastName
address
age
This is the basic idea behind Object Oriented Programming. It's a lot easier to comprehend when you look at objects as actual physical objects. It makes it easier to understand the relationships.
Yes, your assumption that calcModel is a variable object of type CalculatorModel is right. when you say calcModel = new CalcModel(); it is actually creating another object in memory for storing the data that is to be stored(both operands) and storing the address of that object in calcModel. This way you can refer to object you created earlier. If you have worked with c earlier you can easily say calcModel is a pointer where as the object created is the data in the address located in the pointer.
The difference between a primitive type variable and object type variable is that the actual data that is to be stored in the variable is much more complex. For example the class CalculatorModel is a combination of two doubles... You can carry both operands as one entity by combining them(encapsulating) in a class. An object may also contain methods that can do some operations on the data stored in its member variables.
It is not necessary to have two classes, some people like it that way. I'm positively sure there is no need to create two classes in this case. Both can be merged as you have obviously did. Mind you there are no right and wrong ways to code, some ways of doing it are more preferable because they are more popular and avoids readability issues in long run. setOperand1() method is just using calcModel.setOperand1() so I don't see a necessity to have it done that way, calcModel.setOperand1 can be called directly from where ever setOperand1() is called. However, there can be case where you want to hide which function of setOperand1 is to be called or some complex operations are to be performed before calling calcModel.setOperand1. In such cases where you want to reduce burden for the callers of calcModel.setOperand1 by created setOperand1().
There is nothing wrong with the code. However you don't have to use getValue1() & getValue2() function in your add, subtract and other mathematical operations. you can simply say return num1+num2 Because, num1 & num2 are member variables of the same class.
private CalculatorModel calcModel;
public CalculatorHelper(){
calcModel=new CalculatorModel();
}
in the calculatorHelper class. Is calcModel a variable a variable of
type CalculatorModel ?What is the difference of having a object as a
data type than a primitive data type to a variable? If calcModel is a
variable what is done by the line calcModel=new CalculatorModel();
The variable calcModel is an instance of CalculatorModel, but is a class variable to the class CalculatorHelper. If you want to know about primitive data type vs object data type, check this article out. This line calcModel=new CalculatorModel(); is initializing the variable. You must do this in order to actually use the methods. Read more here.
I don't understand why it is important to have two classes as
CalculatorModel and CalculatorHelper.
There are cases where helper classes/methods are useful when it comes to separating large chunks of logic. Check this article out.
public void setOperand1(double value){
calcModel.setOperand1(value);
}
in the helper class as there's already a setmethod in CalculatorModel
class.
Yes, and it's calling that same exact set method but from the CalculatorHelper class.
This is what I tried and what's wrong with this code?
There seems to be nothing wrong with the code. I'm assuming you're using it properly from the main method (or whatever method you're using the class in).
This is essentially a Delegate Pattern by which the author has implemented the Calculator.
The Calculator serves the abstraction of the real-life Calculator.
By providing the helper/delegate class , I separate the behavior of the object.I am free to write my own implementation of add / subtract using a helper class. Calculator will serve as the Model of your calculations.
Consider this , If you try to modify the behavior you need to change the whole Calculator class and distribute it to the Client. However , I don't have to modify the Calculator but only the Helper which the client does/might not ship.
There is nothing wrong in what you have done - but consider this - what if you want to have Single instance of the Calculator - you can control instantion using helper class (in this case)
private CalculatorModel calcModel;
public CalculatorHelper(){
calcModel=new CalculatorModel();
}
is composition which is used here to separate concerns. The CalculatorHelper's concern is to know how to do addition, substraction, .. while the CalculatorModel knows the values, how to provide them to the outside and how to store them.
CalculatorHelperhas therefore an instance ofCalculatorModel` to which it can delegate all the things it does not know about. E.g.
public void setOperand1(double value){
calcModel.setOperand1(value);
}
The overall design is still questionable. First of all is it a bad encapsulation of a "calculator" because none of math operation reflect back to the model in any way. There needs to be a third class (CalculatorHelperHelper?) that knows how to deal with more than two operands.
It is also questionable whether or not a CalculatorModel should have two values at once. Two separate value objects would IMO make a lot more sense and would result in more modular code that would also be easier to understand as composition of objects.
The last point in this example is that encapsulating "storage" of values into CalculatorModel does not provide any real benefit here. It would if there was some kind of database backend or otherwise "complicated" logic that does not belong into CalculatorHelper. I would have taken more or less your approach in a simple real world scenario. Your code is not wrong. It's just a different approach.
The code in the context of the book and given that it is an example to show some design techniques is ok for that purpose. I would just do it very much different if I was to write a calculator. OO design is on the other hand not right or wrong and people can argue a lot about what good design is.

sending value to another method in another class in JAVA

sorry I'm new to java. I want to pass the mark1 to class Exam in method Calculator, but I got some error how can i do that the program say incompatibe type. What can I do?
I want to send mark1 from this method:
public float SendMark(){
Exam ex = new Exam();
for (int i=0; i<students.length; i++) {
mark1 = students[i].getMark();
}
return ex.Calculator(mark1);
}
to this class and method calculator ... but it say incompatible type ... to this method i want to sum the Array value and get average of the array values ... is it correct way ?? what should i write here ...? please help me details thanks ...
public class Exam {
public Calculator (float mark1) {
AddList ad = new AddList();
}
}
you are missing the return type for the method calculator.
public Calculator (float mark1)
should be
public float Calculator (float mark1)
Your Calculator method does not have a return statement and its signature (the method header) does not declare a return type.
Also, I can't see where you declared mark1, you only initialized it in the for loop.
Meanwhile, I also spotted a logic error, the mark1 will always send the last score in the array because its value would be repeatedly overwritten in the loop; only the last value survives.
When you do not need return type, you type void method_name(args), like in C. Void is the placeholder for no return type. Secondly, your code is better than of other noobs, but you still have a lot of unnecessary details, which means that you did not debug yourself. Localize the problem better (remove everything unnecessary to reproduce). It will be simpler then for experts to see your problem immediately. You will even see or guess it yourself. Otherwise, without learning localizing the bugs, you will never become a programmer. And garbage the SO unnecessarily.
there are several small problems in your codes:
usually method name should start with lower letter in java code convention
what does the for loop in SendMark method do? just overwrite a float variable many times?
in your comment, you mentioned you want Exam.Calculator method print result, but no return value. Then you should add void as return type to method Calculator().
if you don't expect any return value from Calculator() method, why you return ex.Calculator(mark1) in your SendMark() method, and type is float?
From what I have understood from your question, here is my answer.
public float **s**endMark(){
Exam ex = new Exam();
for (int i=0; i<students.length; i++) {
mark1 = students[i].getMark(); //this does not make any sense.
}
//Since you insisted that you wanted to only print, just call the calculator method and do not return anything. change the return type of calculator method to void.
ex.Calculator(mark1);
return "something";//since your method's definition says so
}
public class Exam {
public void **c**alculator (float mark1) {
//Do your stuff
}
}
You may also want to look into sun java's coding conventions.
one of the approach is to pass your students array to calculator and inside calclator method iterate over student sum up marks like
marks = marks + students[i].getMark() and avg = marks/students.length
other could be, form marks i your main method by marks = marks + students[i].getMark() and then pass marks and length to calculator method to calculate average.
Also please go through java coding conventions and how to pick return types.
hope this helps.

Categories