Java - Field in parent class not changing - java

So, I have a variable in a parent class that I am trying to change in a subclass with getter/setter methods. But, the value is just staying the same and I have no idea why.. What am I doing wrong? Any help is appreciated!
Here is a breakdown of the program: In the driver class, you choose what you want to do, then it uses the current value variable and a number you choose (operand2) to get the answer. The add, subtract, multiply and divide are in the memory calculator class. It can also clear, which sets the current value variable to zero. Now, we are adding a sub class to it that does exponents and logarithms.
specifics: The variable currentValue in the MemoryCalc class stays the same when I try to use the power or log methods in the ScientificMemCalc class. In that class it uses a getter method to get the current value and then attempts to use a setter method to change the current value. But nothing changes. And another problem: the getter method gets a zero value from the currentValue field.
Here is driver class with main method:
package ScientificMemCalc;
import java.util.Scanner;
import ScientificMemCalc.MemoryCalc;
public class ScientificCalcDriver {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
MemoryCalc calculator = new MemoryCalc();
ScientificMemCalc scientificCalc = new ScientificMemCalc();
int menu = 0;
double operand2, answer;
while (menu !=8) {
answer = calculator.getCurrentValue();
System.out.println("The current value is: " + answer);
menu = getMenuOption();
switch(menu) {
case 1:
// Add
operand2 = calculator.getOperand("What is the second number?: ");
calculator.add(operand2);
break;
case 2:
// Subtract
operand2 = calculator.getOperand("What is the second number?: ");
calculator.subtract(operand2);
break;
case 3:
// Multiply
operand2 = calculator.getOperand("What is the second number?: ");
calculator.multiply(operand2);
break;
case 4:
// Divide
operand2 = calculator.getOperand("What is the second number?: ");
calculator.divide(operand2);
break;
case 5:
// Power
operand2 = calculator.getOperand("What is the second number?: ");
scientificCalc.power(operand2);
break;
case 6:
// Logarithm
scientificCalc.log();
break;
case 7:
// Clear
operand2 = 0;
calculator.clear();
break;
case 8:
// Quit
System.out.println("Goodbye!");
break;
}
}
}
public static int getMenuOption() {
Scanner input = new Scanner(System.in);
int choice = 0;
// Display menu
System.out.println("Menu:");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Power");
System.out.println("6. Logarithm");
System.out.println("7. Clear");
System.out.println("8. Quit");
// Get menu input
System.out.print("What would you like to do?: ");
choice = input.nextInt();
while (choice < 1 || choice > 8) {
System.out.print("Invalid. Try again: ");
choice = input.nextInt();
}
return choice;
}
}
Here is the memory calculator class:
package ScientificMemCalc;
import java.util.Scanner;
public class MemoryCalc {
private double currentValue;
public double getOperand(String prompt) {
Scanner input = new Scanner(System.in);
System.out.print(prompt);
return input.nextDouble();
}
public double getCurrentValue() {
return currentValue;
}
public void setCurrentValue(double temp) {
currentValue = temp;
}
public void add(double operand2) {
// Add
currentValue += operand2;
}
public void subtract(double operand2) {
// Subtract
currentValue -= operand2;
}
public void multiply(double operand2) {
// Multiply
currentValue *= operand2;
}
public void divide(double operand2) {
// Divide
if (operand2 == 0) {
System.out.println("You cannot divide by zero!");
currentValue = Double.NaN;
}
else {
currentValue /= operand2;
}
}
public void clear() {
// Clear
currentValue = 0;
}
}
And finally the subclass to add scientific functions:
package ScientificMemCalc;
public class ScientificMemCalc extends MemoryCalc {
public void power(double operand2) {
// Power
double currentValue = getCurrentValue();
double temp = Math.pow(currentValue, operand2);
setCurrentValue(temp);
}
public void log() {
// Logarithm
double currentValue = getCurrentValue();
double temp = Math.log(currentValue);
setCurrentValue(temp);
}
}

Short answer
You're interacting with TWO DIFFERENT OBJECTS calculator and scientificCalc. They do not share any state.
What can you do?
Use scientificCalc for all the calculations. Thus the value will be one and only.
cons : the things can become much more complicated once you introduce another calculator types
Pass the calculator to constructor of ScientificMemCalc as a constuctor parameter.
cons : same as for #1
Use a separate class/object for storing the state. (as suggested by #user2864740)
Do not store the state inside the calculator (Why would you need that?). Pass all the operands (current state will be always operand #1) to the methods and return the result to caller:
int menu = 0;
double operand2, answer;
while (menu !=8) {
// You don't need this line
//answer = calculator.getCurrentValue();
System.out.println("The current value is: " + answer);
menu = getMenuOption();
switch(menu) {
case 1:
// Add
operand2 = calculator.getOperand("What is the second number?: ");
//
answer = calculator.add(answer, operand2);
break;
//... modify other operations in the same way
}

In the ScientificMemCalc class you extend MemoryCalc, this lets ScientificMemCalc call the methods created in MemoryCalc and provides access to its own set of variables in MemoryCalc. However, when creating two separate objects of each class, they will both have access to a variable of the same name and type, but they will be two separate variables in two separate objects.
One solution is passing in a MemoryCalc object into the constructor of the ScientificMemCalc class then calling the getCurrentValue()/setCurrentValue() methods in respects to that object. Allowing access to the same variable.
package scientificMemCalc;
public class ScientificMemCalc {
//store the MemoryCalc object so we have access to the needed data
private MemoryCalc memCalc;
//store the MemoryCalc
public ScientificMemCalc(MemoryCalc memCalc) {
this.memCalc = memCalc;
}
public void power(double operand2) {
// Power
double currentValue = memCalc.getCurrentValue();
double temp = Math.pow(currentValue, operand2);
memCalc.setCurrentValue(temp);
}
public void log() {
// Logarithm
double currentValue = memCalc.getCurrentValue();
double temp = Math.log(currentValue);
memCalc.setCurrentValue(temp);
}
}
Then when instantiating your ScientificMemCalc object pass in the reference for your MemoryCalc.
MemoryCalc calculator = new MemoryCalc();
ScientificMemCalc scientificCalc = new ScientificMemCalc(calculator);
Hope this helps!

Related

How can I add a method that returns a result?

I have been working on these programs.
They don't have any errors but I need to make them return a result in order for them to work properly. More specifically to add a method that returns a result.
The instructions were the following:
Write a program that is split in to methods at least one of which returns a result
This is the first program:
import java.util.Scanner; // Needed to make Scanner available
public class onlineCalculator {
public static void main(String[] args) {
Calculator();
} //END of main method
// Inserting your loan at the start of the year and the amount paid off
// and calculates the amount yet to pay with interest
//
public static void Calculator(){
int a;
int b;
Scanner scanner = new Scanner(System.in);
System.out.print("Amount of loan at start of year? ");
a = scanner.nextInt();
System.out.print("Amount paid off this year? ");
b = scanner.nextInt();
int c;
c= a - b;
double d;
final double e;
d = c * 1.07 * 10.0;
e = (int)d / 10.0;
System.out.println("The new amount owed is (in pounds): " + e);
} //END of Calculator
}
This is the second program:
import java.util.Scanner; // Needed to make Scanner available
public class BodyAge {
public static void main(String[] args) {
CalculateAge();
} // END of main method
// Inserting age and heart rate and stretch distance
//and calculates the body age based on conditions
public static void CalculateAge() {
int age;
int heartRate;
int stretch;
Scanner input = new Scanner(System.in);
System.out.print("What is your age? ");
age = input.nextInt();
System.out.print("What is your heart rate? ");
heartRate = input.nextInt();
if (heartRate <= 62) {
age -= 5; // block of code to be executed if condition1 is true
} else if (62 <= heartRate && heartRate <= 64) {
age--; // block of code to be executed if the condition1 is false and condition2 is
// true
} else if (65 <= heartRate && heartRate <= 70) {
age++; // block of code to be executed if the condition1 and condition2 are false and
// condition3 is true
} else {
age += 2; // block of code to be executed if the condition1 and condition2 and condition3
// are false and condition4 is true
}
System.out.print("How far can you stretch? ");
stretch = input.nextInt();
if (stretch <= 20) {
age += 4; // block of code to be executed if condition1 is true
} else if (20 <= stretch && stretch <= 32) {
age++; // block of code to be executed if the condition1 is false and condition2 is
// true
} else if (33 <= stretch && stretch <= 37) {
age = age + 0; // block of code to be executed if the condition1 and condition2 are false and
// condition3 is true
} else {
age = age + 3; // block of code to be executed if the condition1 and condition2 and condition3
// are false and condition4 is true
}
System.out.println("Your body's age is " + age);
} //END of CalculateAge
}
Here's an example of one possible way you might consider breaking up a class into using some methods with returns. Let's take your first class for this example. You frequently are taking input from your user.
Scanner scanner = new Scanner(System.in);
System.out.print("Amount of loan at start of year? ");
a = scanner.nextInt();
System.out.print("Amount paid off this year? ");
b = scanner.nextInt();
This could potentially be broken out into another method for condensed reusability.
public static int askForInt(Scanner scanner, String message) {
System.out.print(message);
return scanner.nextInt();
}
From there you can replace your calls for information with this method. Full example:
import java.util.Scanner; // Needed to make Scanner available
public class OnlineCalculator {
public static void main(String[] args) {
calculator();
} //END of main method
// Inserting your loan at the start of the year and the amount paid off
// and calculates the amount yet to pay with interest
//
public static void calculator(){
int a;
int b;
Scanner scanner = new Scanner(System.in);
a = askForInt(scanner, "Amount of loan at start of year? ");
b = askForInt(scanner, "Amount paid off this year? ");
scanner.close();
int c;
c= a - b;
double d;
final double e;
d = c * 1.07 * 10.0;
e = (int)d / 10.0;
System.out.println("The new amount owed is (in pounds): " + e);
} //END of Calculator
public static int askForInt(Scanner scanner, String message) {
System.out.print(message);
return scanner.nextInt();
}
}
First program,
You could for example split your calculate() method into 2 method and move your int variable "a" and "b" in the main() method
1ST method:
void getInput(){
...
}
2nd method:
int calculateAndreturnResult(int a, int b) {
...
}
Finally use those method in the main() and print the result :
getInput();
int result = calculateAndreturnResult(){
}
system.out.println(result);
So how Java will work is the compiler will only read commands from the "main" method. So in the case of the calculator, Java will see that you want to run the calculator method, which has a return type of "void" It goes PUBLIC (meaning other classes can see and interact with it) STATIC (basically meaning that the method belongs to the class itself, not instances of the class) VOID ( this is your return type, meaning after the method is done, what is being put back into main) so if you want a method to return something, you need to change the return type. In the case of your calculator project something like this would split it up into 2 methods one of which returns something:
public class OnlineCalculator {
public static void main(String[] args) {
Calculator();
} //END of main method
// Inserting your loan at the start of the year and the amount paid off
// and calculates the amount yet to pay with interest
//
//this will return an int type
public static int loanDifference(int amountOwed, int amountPaid) {
int c = amountOwed - amountPaid;
return c;
}
// this will return a double type
public static double newAmountOwed(double d) {
double e = (int)d / 10.0;
return e;
}
public static void Calculator(){
int a;
int b;
Scanner scanner = new Scanner(System.in);
System.out.print("Amount of loan at start of year? ");
a = scanner.nextInt();
System.out.print("Amount paid off this year? ");
b = scanner.nextInt();
scanner.close();
int c = loanDifference (a, b);
double d;
d = c * 1.07 * 10.0;
final double e = newAmountOwed(d);
System.out.println("The new amount owed is (in pounds): " + e);
} //END of Calculator
}
seems like they want you to put more code in, but the idea is that they want you to know how to use methods that work together to make something at the end!
use the same idea with the other one!

Can I get help figuring out this?

When i run my code, I get an error in mimir (idk if you guys know about it but is a platform that teachers use to check the test cases of the code that you submit) saying that I a have a whitespace that shouldn't be there (check image).
1.) how can i fix that regarding my code.
and another issue which it drove me crazy is,
how can I make it so that when I enter a letter, In this case it was inputted 'f' (check the image) to display the "enter two integers:" just like the imagine. I tried different types of loops and changing the layout but i never got it to be correct.
p.d. Yes, this was a homework and was due yesterday. Even though i got a good grade on it, it still bugged me that I couldn't figure out these two things out.
import java.util.InputMismatchException;
import java.util.Scanner;
public class MathTeacher {
public static int addNumbers(int n1, int n2){
int add = n1+n2;
return add;
}
public static int subtractNumbers(int n1, int n2){
int subs = n1-n2;
return subs;
}
public static int multiplyNumbers(int n1, int n2){
int mulp = n1*n2;
return mulp;
}
public static int divideNumbers(int n1, int n2){
int div = n1/n2;
return div;
}
private static int getIntFromUser(Scanner scan) {
int x;
while (true) {
try {
x = scan.nextInt();
break;
} catch (InputMismatchException e) {
scan.next();
}
}
return x;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Welcome to *Mental Math Practice* where you can test your addition, subtraction, multiplication, and division.");
Scanner scanner = new Scanner(System.in);
System.out.println("Enter two integers: ");
String typeQuit= "";
do {
int choices;
int n1 = getIntFromUser(scanner);
int n2 = getIntFromUser(scanner);
System.out.println("Enter 1 to add the two numbers.");
System.out.println("Enter 2 to subtract the second number from the first number.");
System.out.println("Enter 3 to multiply the two numbers.");
System.out.println("Enter 4 to divide the first number by the second number.");
choices = scanner.nextInt();
switch (choices) {
case 1: {
int add = addNumbers(n1, n2);
System.out.println(add);
break;
}
case 2: {
int sub = subtractNumbers(n1, n2);
System.out.println(sub);
break;
}
case 3: {
int mulp = multiplyNumbers(n1, n2);
System.out.println(mulp);
break;
}
case 4: {
int div = divideNumbers(n1, n2);
System.out.println(div);
break;
}
}
System.out.println("Enter 'Quit' to end the program.");
typeQuit = scanner.next();
} while(!typeQuit.equals("Quit"));
}
}

Memory Calculator confusion java

In my class we needed to make a memory calculator in Java. Im really new to Java and had help making the program. Turned it in and the teacher said "Please separate the MemoryCalculator class from the class with the main() method. Currently the way you have created the class, there is no reason to create an instance of the class. But the point of the assignment is to use separate classes and objects." Its been a super long week and midterms and just lost at this time. Any help would be great.
import java.util.Scanner;
public class MemoryCalculator {
private double currentValue;
//Methods
//Scanner
public static int displayMenu(){
Scanner input = new Scanner(System.in);
System.out.print("Lets do some math! \nMenu \n1. Add \n2. Subtract \n3. Multiply \n4. Divide \n"
+ "5. Clear \n6. Quit \n\nWhat would you like to do? ");
int menuChoice = input.nextInt();
return menuChoice;
}
public static double getOperand(String prompt) {
Scanner input = new Scanner(System. in );
double operand;
System.out.println(prompt);
operand = input.nextDouble();
return operand;
}
//Current Value
//Gets
public double getCurrentValue() {
return currentValue;
}
//Setter
public void setCurrentValue(double currentValue) {
this.currentValue = currentValue;
}
//Add
public void add(double operand2) {
currentValue += operand2;
}
//Subtract
public void subtract(double operand2) {
currentValue -= operand2;
}
//Multiply
public void multiply(double operand2) {
currentValue *= operand2;
}
//Divide
public void divide(double operand2) {
if (operand2==0){
setCurrentValue(0);
}
currentValue /=operand2;
}
//Clear
public void clear() {
currentValue = 0;
}
//Main part of the calculator
public static void main(String[] args) {
MemoryCalculator instance = new MemoryCalculator();
double operand;
boolean repeat = true;
while (repeat) {
System.out.println("The current value is: " + instance.getCurrentValue() + "\n");
int menuChoice;
menuChoice = displayMenu();
if (menuChoice > 6 || menuChoice < 1){
System.out.println("I'm sorry, " + menuChoice + " wasn't one of the options\n");
}
switch(menuChoice){
case 1:
operand = getOperand("What is the second number?");
instance.add(operand);
break;
case 2:
operand = getOperand("What is the second number?");
instance.subtract(operand);
break;
case 3:
operand = getOperand("What is the second number?");
instance.multiply(operand);
break;
case 4:
operand = getOperand("What is the second number?");
instance.divide(operand);
break;
case 5:
instance.clear();
break;
case 6:
System.out.println("Goodbye have a great day");
System.exit(0);
break;
}
}
}
}
What it looks like you did with your program was create one, single, class that holds all of the code for your calculator program, within which you instantiated an object of the same class.
What your teacher wants instead, is for you to have two separate classes, one which contains the code that makes the calculator work, and another class where you instantiate an object of the first class, and call the methods contained within that class.
For your assignment, what I would suggest would be to create a new class, perhaps called Main, where your program's Main() method will be, and keep all of the code for the calculator program in the MemoryCalculator class. From there, you can instantiate an object of MemoryCalculator class (which you already did, called instance) and use method calls to reference methods and attributes from within the MemoryCalculator class.
This may require reworking some of your code so that it runs properly, given that you'll be calling most of it from an object of the MemoryCalculator class, but it should be doable.

Unexpected output in a java program

I have written the following java code where I am getting 0 for area of A triangle. What can be the reason for this erroneous output?
package methodoverrideoverload;
import java.io.*;
import java.util.*;
class Figure_Area {
int dima;
int dimb;
Figure_Area()
{
}
Figure_Area(int i, int j)
{
dima=i;
dimb=j;
}
void cal_area()
{
System.out.println("Area is undefined!!");
}
}
class Figure_Area_Tri extends Figure_Area {
Figure_Area_Tri(int i, int j)
{
super(i,j);
}
void cal_area()
{
System.out.println("The area of the Triangle is "+((1/2)*dima*dimb));
}
}
class Figure_Area_Rec extends Figure_Area {
Figure_Area_Rec(int i, int j)
{
super(i,j);
}
void cal_area()
{
System.out.println("The area of the Rectangle is "+ dima*dimb);
}
}
class Figure_Area_Cir extends Figure_Area {
double pi=3.14;
Figure_Area_Cir(int i)
{
super.dima=i;
}
void cal_area()
{
System.out.println("The area of the Circle is "+ (pi*dima*dima));
}
}
class findArea {
public static void main(String args[]) throws IOException
{
System.out.println("<<-MENU-->>");
System.out.println("Enter the figure you want to know the area of->");
System.out.println("Press 1 for Triangle");
System.out.println("Press 2 for Rectangle");
System.out.println("Press 3 for Circle");
System.out.println("Press 4 to Exit");
System.out.println("Enter your choice->");
Scanner sc=new Scanner(System.in);
int ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter Height->");
int h=sc.nextInt();
System.out.println("Enter Base->");
int b=sc.nextInt();
Figure_Area_Tri tri=new Figure_Area_Tri(h,b);
tri.cal_area();
break;
case 2:
System.out.println("Enter Length->");
int len=sc.nextInt();
System.out.println("Enter Breadth->");
int bre=sc.nextInt();
Figure_Area_Rec rec=new Figure_Area_Rec(len,bre);
rec.cal_area();
break;
case 3:
System.out.println("Enter Radius->");
int rad=sc.nextInt();
Figure_Area_Cir cir=new Figure_Area_Cir(rad);
cir.cal_area();
break;
case 4:
break;
default:
System.out.println("Sorry! Invalid Choice");
}
}
}
I have examined the code in debugging mode and found out the values of dima and dimb are set as the input value, but somehow the function for area is most likely unable to give the correct result.
With integers variables java uses integer maths, for example
1/2==0
To solve this use double maths
1.0/2==0.5
1d would also work instead of 1.0
So in your case
(1.0/2)*dima*dimb
As long as one of the variables is a double then double maths applies (be careful when the equation contains multiple "parts", each part must have a double in it).
What won't help and why
Note just casting to double ((double)(1/2)*dima*dimb) won't solve the problem because the detail is already lost by the point of the cast to double, it goes as
(double)(1/2)*dima*dimb
(double)(0)*(dima*dimb)
(double)(0)
0.0
You are using 1/2 which equals 0
You need to use a double, so 1.0 / 2.0 = 0.5
Try using double or float for 1/2.
If you use integers it will be 0 as there is no such thing as 0.5 with integers.
You can write 1/2f for example or 1/2d or look at other answers :)

Multi Class program

Hi I was attempting to create a calculator that can add subtract multiply and divide to challenge myself but find myself getting stuck around the switch part:(I will point out the errors within the switch message that say "The method addition etc(String[]) in the type addition etc is not applicable for the arguments ()." I believe the problem lies within the public void of the other classes.
Script:
public class ComputronCalc {
public static void main(String args[]) {
int mode;
mode = 1;
Addition ADD = new Addition();
Subtraction SUB = new Subtraction();
Multiplication MUL = new Multiplication();
Division DIV = new Division();
System.out.println("Hello welcome to the Computron fully functional calculator, coded by Samuel Cole, designed by Dwight Schrute.");
switch(mode) {
case 1:
ADD.Addition();<-----------addition is underlined in red
break;
case 2:
SUB.Subtraction();<-------------same
break;
case 3:
MUL.Multiplication();<---------------same
break;
case 4:
DIV.Division();<----------------same
break;
default:
System.out.println("You have not selected a mode, do so by editing the mode variable in the source.");
}
System.out.println("Thank you for choosing Computron.");
}
}
import java.util.Scanner;
public class Addition {
public void Addition(String Args[]) {
Scanner input = new Scanner(System.in);
double fnum, snum, answer;
System.out.println("Type the first number you desire to calculate.");
fnum = input.nextDouble();
System.out.println("Type the second number you desire to calculate.");
snum = input.nextDouble();
System.out.println("Calculating...");
answer = fnum + snum;
System.out.println(answer);
}
}
import java.util.Scanner;
public class Multiplication {
public void Multiplication(String Args[]) {
Scanner input = new Scanner(System.in);
double fnum, snum, answer;
System.out.println("Type the first number you desire to calculate.");
fnum = input.nextDouble();
System.out.println("Type the second number you desire to calculate.");
snum = input.nextDouble();
System.out.println("Calculating...");
answer = fnum * snum;
System.out.println(answer);
}
}
import java.util.Scanner;
public class Division {
public void Division(String Args[]) {
Scanner input = new Scanner(System.in);
double fnum, snum, answer;
System.out.println("Type the first number you desire to calculate.");
fnum = input.nextDouble();
System.out.println("Type the second number you desire to calculate.");
snum = input.nextDouble();
System.out.println("Calculating...");
answer = fnum / snum;
System.out.println(answer);
}
}
note: I'm using eclipse so each class is on like a different page.
Your methods expect the argument "args", which you don't use. Remove it. For example:
public void Addition(String Args[]) {
becomes:
public void Addition() {
(by the way, your code does not follow Oracle Java Naming Convention)
While the acute problem is that you need to change your method signatures to not have any parameters or change the method invocation to send a parameter, I think there is a better solution you should concider.
Change the methods in your operation classes to be constructors:
public class Addition {
public Addition() {
//...
}
}
Then you do not need to instantiate all the operations for each run and the switch becomes:
switch(mode) {
case 1:
Addition();
break;
case 2:
Subtraction();
break;
case 3:
Multiplication();
break;
case 4:
Division();
break;
default:
System.out.println("You have not selected a mode, do so by editing the mode variable in the source.");
}
Do not have any parameter (in this program, the String[] args parameter) for the function inside the four operator classes. Your program should work without them.
public class Addition {
public Addition() {
//...
}
}
Same applies for other classes too.
public class Subtraction {
public Subtraction() {
//...
}
}
public class Multiplication{
public Multiplication() {
//...
}
}
public class Division {
public Division() {
//...
}
}

Categories

Resources