Multiple class calculator - java

I am trying to make a simple calculator using multiple classes. I can make one in one class, but now I would like to try making one using two classes. I am having trouble with calling some variables (fnum, snum, answer) from the OperationClass.
If I run the program as it's written now I get 0 returned for the answer.
I tried making the variables fnum, snum and answer in OperationClass public but that did not work.
Also I tried public class OperationClass extends Calculator. That did not work either.
I know i'm missing something very simple. I just can't pin point it.
Calculator Class:
import java.util.Scanner;
public class Calculator{
public static void main(String[] args) {
OperationClass operationObject = new OperationClass();
Scanner input = new Scanner(System.in);
double userInput;
int userChoice;
System.out.print("Please Enter The First Number: ");
userInput = input.nextDouble();
System.out.print("Please Enter The Second Number: ");
userInput = input.nextDouble();
System.out.println("Please Select Operation to Perform:");
System.out.println("1-Addition");
System.out.println("2-Subtraction");
System.out.println("3-Division");
System.out.println("4-Multiplication");
userChoice = input.nextInt();
switch (userChoice){
case 1:
operationObject.addition();
System.out.println();
break;
case 2:
operationObject.subtraction();
break;
case 3:
operationObject.division();
break;
case 4:
operationObject.multiplication();
break;
}
}
}
OperationClass:
public class OperationClass{
double fnum, snum, answer;
public void addition(){
answer = fnum + snum;
System.out.println(answer);
}
public void subtraction(){
answer = fnum - snum;
System.out.println(answer);
}
public void division(){
answer = fnum / snum;
System.out.println(answer);
}
public void multiplication(){
answer = fnum * snum;
System.out.println(answer);
}
}

You aren't setting fnum and snum in OperationClass to anything, so their value is zero. Delete those member variables, and change your addition() subtraction() etc. methods to take them as parameters, like this:
public void addition(double fnum, double snum) {
answer = fnum + snum;
System.out.println(answer);
}

First, you need to store the two inputed values to different variables, so the second won't overwrite the first:
System.out.print("Please Enter The First Number: ");
fnum = input.nextDouble();
System.out.print("Please Enter The Second Number: ");
snum = input.nextDouble();
Once inputed, you can pass these variables to the OperationClass's methods:
public class OperationClass{
public void addition(double fnum, double snum){
double answer = fnum + snum;
System.out.println(answer);
}
public void subtraction(double fnum, double snum){
double answer = fnum - snum;
System.out.println(answer);
}
public void division(double fnum, double snum){
double answer = fnum / snum;
System.out.println(answer);
}
public void multiplication(double fnum, double snum){
double answer = fnum * snum;
System.out.println(answer);
}
}

You need to pass the values entered by the user to the OperationClass class.
There are multiple ways of doing this.
1) Option one. Change the methods to accept some parameters, for example:
public double addition(double fnum, double snum ){
return fnum+snum;
}
and to get the result in the Calculator you can do this:
case 1:
System.out.println(operationObject.addition(userInput1, userInput2));
break;
You have to store the user input in 2 different variables.
2) Store the user's input in the OperationClass as class variables.
public class OperationClass{
.....
public void setFNum(double fnum){
this.fnum = fnum
}
public void setSNum(double snum){
this.snum = snum
}
......
}
and to pass the values from the Calculator you can do this.
public static void main(String[] args) {
....
OperationClass operationObject = new OperationClass();
Scanner input = new Scanner(System.in);
double userInput;
userInput = input.nextDouble();
operationObject.setFNum(userInput);
userInput = input.nextDouble();
operationObject.setSNum(userInput);
....
}

You collect the two numbers into one variable called userInput. The first gets overwritten by the second, then you never reference it again. For your OperationClass to do something with those values, you should have methods to set the values, or pass them to the operation being performed as parameters.
For the first case you could add setter methods like this:
public void setFNum(double f) {
fnum = f;
}
public void setSNum(double s) {
snum = s;
}
Then in main, after getting a value from the user, set it using those methods.
System.out.print("Please Enter The First Number: ");
userInput = input.nextDouble();
operationObject.setFNum(userInput);
System.out.print("Please Enter The Second Number: ");
userInput = input.nextDouble();
operationObject.setSNum(userInput);
A second way is that you could make the methods in OperationClass take both numbers as parameters and never set it internally.
public void multiplication(double fnum, double snum){
answer = fnum * snum;
System.out.println(answer);
}

You need to pass the first and second ints as parameters. This involves re-writing your method objects to accept 2 parameters, or creating a constructor that accepts 2 parameters and instantiating the object after the numbers have been inputted.
To create the constructor, (which will allow you to set the variables in the class and use them):
public OperationClass(int fnum, int snum){
this.fnum = fnum;
this.snum = snum;
}
Then you call it when instantiating the object (again, after the numbers have been inputted) using:
OperationClass operationObject = new OperationClass(firstInput, secondInput);
You'll also need to modify your input so that the 2 inputs go in different variables. This is so that they can be passed as parameters.

Related

Java Method isn't implementing what it is supposed to

Hey everyone very new to coding!
So I was trying to make a calculator program using object oriented programming in Java however when I try to call my method for addition it doesn't do the job entirely so what am I doing wrong here ?
Thanks in advance :)
import java.util.Scanner;
public class CalculatorOOP {
Scanner input = new Scanner(System.in);
public static double currentValue;
public double valueInput;
public CalculatorOOP(double valueTyped){
valueTyped = currentValue;
}
public double addToValue(){
System.out.println("Type the value you want to add:");
double valueToAdd = input.nextDouble();
double valueAfterAddition = CalculatorOOP.currentValue + valueToAdd;
return valueAfterAddition;
}
public double substractToValue(){
System.out.println("Type the value you want to substract:");
double valueToSubstract = input.nextDouble();
double valueAfterSubstraction =
CalculatorOOP.currentValue - valueToSubstract;
return valueAfterSubstraction;
}
public double multiplyValue(){
System.out.println("Type the factor value:");
double factor = input.nextDouble();
double valueAfterMultiplication = CalculatorOOP.currentValue * factor;
return valueAfterMultiplication;
}
public double divideValue(){
System.out.println("Type the divisor value:");
double divisor = input.nextDouble();
double valueAfterDivision = CalculatorOOP.currentValue / divisor;
return valueAfterDivision;
}
}
import java.util.Scanner;
public class Main {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Type a value:");
double valueInput = input.nextDouble();
CalculatorOOP obj = new CalculatorOOP(valueInput);
System.out.println("Enter the calculation option (1, 2, 3, or 4):");
int optionEntered = input.nextInt();
switch (optionEntered){
case 1 : obj.addToValue();
}
}}
Here this is what I get when running the code however it is not performing the addition it is just asking for values
Type a value:
2
Enter the calculation option (1, 2, 3, or 4):
1
Type the value you want to add:
4
Process finished with exit code 0
Your addToValue method seems to perform the addition correctly and return the calculated sum. Where you call the method, you are not picking up the return value — so it just disappears, is discarded. I believe you want to assign it back into CalculatorOOP.currentValue and/or print it. Either from inside the method or from where you called it.

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.

Cannot find symbol on a printf line

Did a little bit of research on this error and most seem simple. I checked to see if i had some spelling errors and I didnt notice any. Im trying to print a few lines using printf. When i go to compile this code it gives me a "cannot find symbol error". Could it be that the method these lines are in need to be in the method the variables are defined? The error is only being done in my printSales method.This isnt the finished product so i may be short a piece or two. But here is my code any help would be appreciated.
import java.util.Scanner;
public class Sales
{
public static void main( String[] args)
{
Scanner input = new Scanner (System.in);
System.out.print("Please enter a product number.");
double product1 = 0;
double product2 = 0;
double product3 = 0;
double product4 = 0;
double product5 = 0;
double sale;
int userInput = input.nextInt();
while(userInput != 0)
{
if(userInput >= 1 && userInput <= 5)
{
switch(userInput)
{
case 1: System.out.println("");
product1 ++;
sale += 2.98;
break;
System.out.print("How many were sold?");
userInput = input.nextInt();
case 2: System.out.println("");
product2 ++;
sale += 4.50;
break;
System.out.print("How many were sold?");
userInput = input.nextInt();
case 3: System.out.println("");
product3 ++;
sale += 9.98;
break;
System.out.print("How many were sold?");
userInput = input.nextInt();
case 4: System.out.println("");
product4 ++;
sale += 4.49;
break;
System.out.print("How many were sold?");
userInput = input.nextInt();
case 5:System.out.println("");
product5 ++;
sale += 6.87;
break;
System.out.print("How many were sold?");
userInput = input.nextInt();
}//end switch
} //end if
else if (userInput != 0)
bSystem.out.println("ERROR: Incorrect Product Number, Please Try Again");
System.out.print("");
userInput = input.nextInt();
}//end while
} //end main
public void printSales()
{
System.out.println();
System.out.printf("Product 1: $%.2f\n", product1);
System.out.printf("Product 2: $%.2f\n", product2);
System.out.printf("Product 3: $%.2f\n", product3);
System.out.printf("Product 4: $%.2f\n", product4);
System.out.printf("Product 5: $%.2f\n", product5);
} //end printSales
} //end class
This is a problem with the scope of your variables. You cannot refer to variables from one method in another method. Try redefining printSales:
public void printSales(int product1, int product2, int product3, int product4, int product5)
{
System.out.println();
System.out.printf("Product 1: $%.2f\n", product1);
System.out.printf("Product 2: $%.2f\n", product2);
System.out.printf("Product 3: $%.2f\n", product3);
System.out.printf("Product 4: $%.2f\n", product4);
System.out.printf("Product 5: $%.2f\n", product5);
} //end printSales
and then of course you will have to change how you call printSales (which I see you are not calling now, but perhaps you will call it in the future):
printSales(product1, product2, product3, product4, product5);
Be sure that product1, product2, etc are all in the same "scope"-- you can't reach into another method, or into an if{} or for{} or while{} block to reference variables.
Four problems...
1
sale might not be initialised...
You declare the sale variable as...
double sale;
As a local variable, it has no default value, so doing something like sale += 2.98 has undefined results.
Simple initialize the variable to a default/starting value...
double sale = 0d;
2
package bSystem does not existbSystem.out.println("ERROR: Incorrect Product Number, Please Try Again");
Typo, it should be System.out.println ;)
3
error: cannot find symbol
System.out.printf("Product 1: $%.2f\n", product1);
The values product1, product2, product3, product4 and product5 have no meaning in printSales as they've only been declared as local variables within main.
Normally, I would suggest making these instance variables, but because you're running within a static context of main, this won't work. Instead, modify the printSales method to take parameters...
public void printSales(double product1, double product2, double product3, double product4, double product5) {
...
}
4
You should be getting a number of warnings about 'unreachable statement, this caused by the fact that youbreakout of theswitch` statement, but attempt to execute code after it...
case 1:
System.out.println("");
product1++;
sale += 2.98;
break;
System.out.print("How many were sold?");
userInput = input.nextInt();
^--- These can't be executed, because of the break before it...
Instead, try moving the code before the break statement....
case 1:
System.out.println("");
product1++;
sale += 2.98;
System.out.print("How many were sold?");
userInput = input.nextInt();
break;
You might like to take a look at the Variables trail and Defining Methods for some more details
The variables "double product1/2/3..." are local variables, i.e. their scope and life-cycle are restricted inside the main method - you cannot reach them from printSales().
To solve the problem and be able to modify/call the variables, make them as fields instead. That is, place them inside the context of the class and not a method.
public class Sales
{
//variables moved into the context of the class, i.e. you can reach them from
//all methods of this class. Furhermore, they have to be static in order to be
//accessed from a static method.
private static double product1 = 0;
private static double product2 = 0;
private static double product3 = 0;
private static double product4 = 0;
private static double product5 = 0;
private static double sale;
public static void main( String[] args)
{
Scanner input = new Scanner (System.in);
System.out.print("Please enter a product number.");
//rest of main method but without vairables
}

Where should scanner go in this program?

I'm working on a program that takes the input of two numbers and then does some different calculations. I have my TwoNumbers class with several different methods to calculate sum, distance, average, etc.
Should I put the scanner in this class, or should I put it in the Main method?
I know this is really basic but I've only been learning java for a couple weeks and I'm having a hard time finding how this should be done/how to get the input to correlate to my instance variables and firstNumber and secondNumber
public class TwoNumbers{
private double firstNumber;
private double secondNumber;
public double getSum()
{
double sum = firstNumber + secondNumber;
return sum;
}
public double getDifference()
{
double difference = firstNumber - secondNumber;
return difference;
}
public double getProduct()
{
double product = firstNumber - secondNumber;
return product;
}
public double getAverage()
{
double average = (firstNumber + secondNumber) / 2;
return average;
}
public double getDistance()
{
double distance = Math.abs(firstNumber - secondNumber);
return distance;
}
public double getMax()
{
double maximum = Math.max(firstNumber, secondNumber);
return maximum;
}
public double getMin()
{
double minimum = Math.min(firstNumber, secondNumber);
return minimum;
}
}
Each class should follow the single responsibility principle. Your TwoNumbers class should only work with the double numbers and perform operations on them, nothing more. Providing the double numbers for this class should be in the client, and also the ability to provide the numbers, which means that the client may define the Scanner or another way to provide the data.
The class you have displayed, the TwoNumbers class, should have no user input in it as it should encapsulate the concept of two numbers and two numbers only. It should be written in such a way that it can be used with a Scanner program or with a GUI program without having to change it. Thus the UI should be in main or in another class.
You would probably want to make a constructor for the class, and within the constructor pass the variables you want. This would mean that you get your input from somewhere else, IE the main method or some other means.
public TwoNumbers(double num1, double num2){
firstNumber = num1;
secondNumber = num2;
}
For example:
public double getSum(firstnumber, secondnumber) // <-- you need pass in the value
{
double sum = firstNumber + secondNumber;
return sum;
}
/*
* somewhere in the main or another method you can delare the first number / 2nd number
* for example:
*/
public void static main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter first number");
firstnumber = input.nextInt();
System.out.println("enter first number");
secondnumber = input.nextInt();
}
After that all you need to do is just calling the method you want to pass the number to.
You need to have a constructor in TwoNumbers:
public class TwoNumbers {
private double firstNumber;
private double secondNumber;
public TwoNumbers(double firstNumber, double secondNumber){
this.firstNumber = firstNumber;
this.secondNumber = secondNumber;
}
}
Then in some other Class, you can have your scanner:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter firstNumber");
double firstNumber = scanner.nextDouble();
System.out.println("Enter secondNumber");
double secondNumber = scanner.nextDouble();
TwoNumbers obj = new TwoNumbers(firstNumber, secondNumber);
//Call methods from TwoNumbers
}
Really the code would work if you put the scanner in the main class or in the TwoNumbers class. The best practice way of doing this would be to place your scanner and any other input/output code in you main class, and the processing/calculation code in another class. Which one you choose will be based on your application, but most of the time you will have the scanner in the main class. So...
public class Driver {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String s;
while((s = in.nextLine()) != "stop"){
TwoNumbers.sum(Double.parseDouble(s.split(" ")[0]), Double.parseDouble(s.split(" ")[1]));
}
in.close();
}
}
public class TwoNumbers{
public static double sum(double a, double b){
return a+b;
}
}
}

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