Basic maths in Java - java

I am learning Java and am working on a basic program where a user can input a cost figure, an inflation percentage and a time (years) in order to calculate a cost including inflation.
I am using three classes, 1 application class, 1 driver class and 1 singular class. I am doing this as per the book to build OOP skills (I know there are simpler procedural / structured methods but that is not the point of my exercise).
The issue I am having that the output answer is $0 regardless of the figures I enter. This should not be the case obviously. If someone could please skim over my code and point me in the right direction I would be grateful.
Application Class:
package priceestimator;
public class PriceEstimator {
public static void main(String[] args) {
CostCalculator CostCalc = new CostCalculator();
CostCalc.calculateCost();
}
}
Driver Class:
public class CostCalculator {
public void calculateCost(){
Calculator calculator = new Calculator();
calculator.calculator();
Calculator years = new Calculator();
years.years();
Calculator inflation = new Calculator();
inflation.inflation();
Calculator price = new Calculator();
price.price();
}
}
Singular Class:
package priceestimator;
import java.util.Scanner;
public class Calculator {
private Scanner myScanner = new Scanner(System.in);
private double cost;
private double time;
private double costDif;
private void setTime(int time){
this.time = time;
}
private double getTime(){
return time;
}
private void setCost(double cost){
this.cost = cost;
}
private double getCost(){
return cost;
}
private void setCostDif(double costDif){
this.costDif = costDif;
}
private double getCostDif(){
return costDif;
}
private void getMyScanner(){
this.myScanner = myScanner;
}
public void calculator(){
System.out.println("Enter the current cost (numbers only):");
cost = myScanner.nextDouble();
}
public void years(){
System.out.println("Enter the time difference in years:");
time = myScanner.nextDouble();
}
public void inflation(){
double costTimeDif;
double decimalConversion;
int percent = 100;
double input;
System.out.println("Enter the current inflation rate percentage (numbers only):");
input = myScanner.nextDouble();
decimalConversion = input / percent;
costTimeDif = time * decimalConversion;
costDif = cost * costTimeDif;
}
public void price(){
double price;
price = costDif + cost;
System.out.println("The estimated price is: $" + price);
}
}
Thanks for your time.

You're using different instances of Calculator in the calculateCost(). Use the same instance to get all the details and to calculate the final price as well.
public void calculateCost(){
Calculator calculator = new Calculator();
calculator.calculator();
calculator.years();
calculator.inflation();
calculator.price();
}
As you're using different instances, each instance has its own copy of the instance variables(which you're ultimately using to calculate the final price) and that's why for each instance only that particular value is being populated. Using the same instance would populate all the values by calling the various methods and thus, the price would be calculated using all the values entered by you via the different methods.

You have:
Calculator calculator = new Calculator();
calculator.calculator();
Calculator years = new Calculator();
years.years();
Calculator inflation = new Calculator();
inflation.inflation();
Calculator price = new Calculator();
price.price();
You are creating a different Calculator for every piece of information you input. Each of those is independent of the others. Instead, you mean:
Calculator calculator = new Calculator();
calculator.calculator();
calculator.years();
calculator.inflation();
calculator.price();
Each Calculator has its own copy of the instance fields (and they're initialized to 0 be default). Setting e.g. the time difference in one does not affect the time difference set in the others.
The objects you instantiate should reflect, conceptually, what you are trying to do. Was your intention to have 4 separate calculators? Or was your intention to have a single calculator with all of the information? Of course, it was the latter -- and your code should reflect that.

Related

How can I change this linear Java Code for a program that adds and subtracts to Object-Oriented Code

I am trying to make a simple android app that can add and subtract numbers, but my challenge is to make sure that the program is Object-Oriented. Currently I have been told that it is linear, but I am confused as to how it has remained linear after trying many times to make it object-oriented. How can I make this object oriented programming. Here is my code.
import java.util.Scanner;
public class addNumbers {
public static void main(String[] args)
{ // Begin main
Scanner input = new Scanner( System.in ); // Instantiate object input
System.out.println("Enter number 1"); // Ask the user to enter number 1
double number1 = input.nextDouble(); // Read the first number
System.out.println("Enter number 2"); // Ask the user to enter number 2
double number2 = input.nextDouble(); // Read the second number
double sum=number1 + number2; // Add the numbers
double difference = number1 - number2; // Subtract number 2 from number1
System.out.printf("\nSum = %f\n", sum); // Print the sum
System.out.printf("Difference = %f", difference); // Print the difference.
}
} // end main
My applications use this boilerplate to execute inside an object. If you start like this, you can add methods as you need them.
public class Demo
{
public static void main (String[] args)
{
final Demo app = new Demo ();
app.execute ();
}
private void execute ()
{
// Do stuff here.
}
}
Whoever gave you this assignment is using wrong and confusing terms, because linear programming is something else. But that's a different topic.
Even though this program is not complex, we can introduce some classes by modelling the flow of the program and/or the math operations.
Here is one idea... we could have a class called Operands, that has a method to read the numbers from the input while it prints instructions to the output. Then it stores these two numbers.
So something like this (I am using static class here instead of just class in case you will put this inside your public class addNumbers)
static class Operands {
public final double first;
public final double second;
public Operands(double first, double second) {
this.first = first;
this.second = second;
}
public static Operands readFromIO(InputStream in, PrintStream out) {
Scanner input = new Scanner(in); // Instantiate object input
out.println("Enter number 1"); // Ask the user to enter number 1
double number1 = input.nextDouble(); // Read the first number
out.println("Enter number 2"); // Ask the user to enter number 2
double number2 = input.nextDouble(); // Read the second number
return new Operands(number1, number2);
}
}
Then we could have another class called Calculator, that has a method to set the operands setOperands(Operands operands) and two methods to get the results for the sum and the difference. The methods could be called getSum and getDifference.
static class Calculator {
private double sum = 0;
private double difference = 0;
public void setOperands(Operands operands) {
sum = operands.first + operands.second;
difference = operands.first - operands.second;
}
public double getSum() {
return sum;
}
public double getDifference() {
return difference;
}
}
Then in the main method of the program, we just need to make an instance of the Calculator class and set the Operands on the instance. We read these operators by calling Operands.readFromIO(...). Then we retrieve the sum and the difference from the calculator instance.
So the code in main looks like this
public static void main(String[] args) {
Calculator c = new Calculator();
Operands operands = Operands.readFromIO(System.in, System.out);
c.setOperands(operands);
System.out.printf("Sum = %f\n", c.getSum()); // Print the sum
System.out.printf("Difference = %f\n", c.getDifference()); // Print the difference.
}
This is just one way to do it with some objects.
Another way could be to use an interface called Operation that contains a calculate(Operands operands) method and have 2 more classes Addition and Subtraction implement the interface. Then you would use those two classes to calculate the results.

Banking interest Q

Im trying to make a program that calculates the compound interest of an account with the principle,interest rate, and years. Im trying to do it with dialogs/ The program has the output the return on the invesment if the principle is left to accumulate.
Im stuck on the calculation part, please help
package firstAssignment;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class thinkingQuestion {
public static void main(String[] args) {
//Banking program that asks user for the amount of money they wish to invest in a
//compound interest account (principle), the interest rate (percent value) and the time frame (years).
Scanner in= new Scanner(System.in);
String principle, interestVal, years;
int newPrinciple,newYears;
double total;
principle=JOptionPane.showInputDialog("How much money would you like to invest?");
interestVal=JOptionPane.showInputDialog("What's the interest rate?");
years=JOptionPane.showInputDialog("How many years?");
//convert from String to integer
newPrinciple=Integer.parseInt(principle);
newYears=Integer.parseInt(years);
double newInterestVal=Integer.parseInt(interestVal);
total=JOptionPane.PLAIN_MESSAGE(newPrinciple*Math.pow(1+ newInterestVal, newYears), newYears);
I deleted somo variables you don't need, I think the main problem is on java syntax for show messages. Here you could see a tutorial:
https://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
import javax.swing.JOptionPane;
public class InterestBanking {
public static void main(String[] args) {
// Banking program that asks user for the amount of money they wish to
// invest in a
// compound interest account (principle), the interest rate (percent
// value) and the time frame (years).
String principle, interestVal, years;
float newPrinciple, newYears;
principle = JOptionPane.showInputDialog("How much money would you like to invest?");
interestVal = JOptionPane.showInputDialog("What's the interest rate?");
years = JOptionPane.showInputDialog("How many years?");
// convert from String to integer
newPrinciple = Float.parseFloat(principle);
newYears = Float.parseFloat(years);
double newInterestVal = Float.parseFloat(interestVal);
//You could change your calculation here if this isn't the need formula
double interest = newPrinciple * Math.pow(1 + newInterestVal, newYears);
//you were assigning the result to a total variable. That's not neccesary
JOptionPane.showMessageDialog(null, "Interest:" + NumberFormat.getCurrencyInstance(new Locale("en", "US")).format(interest) + " In years: " + newYears);
}
}

Input/Output - Arithmetic Equation

I am brand new to Java, started two weeks ago and am having issues wrapping my mind around this issue. I have a problem in a class I am taking that has been brought up before. Converting kilograms to pounds and rounding to the second decimal place.
I can create the input side of things and bring up a dialog box to prompt the user to enter in a weight. I can also create an output that uses an equation I made to output the answer in a dialog box.
My question is how do I take the information that is input and use it to convert from kilograms to pounds?
I have been reading my book and scouring the internet trying to find an answer and I think I may be over thinking it. Thanks for the help.
Input.java:
//This program asks a user to input a weight in kilograms.
package module2;
import javax.swing.*;
public class Input {
public static void main(String[] args) {
String weight;
weight = JOptionPane.showInputDialog("Enter weight in kilograms");
}
}
Output.java:
//This program outputs a converted weight from kilograms to pounds.
package module2;
import javax.swing.JOptionPane;
public class Output {
public static void main(String[] args) {
double kg = 75.5;
double lb = 2.2;
double sum;
sum = (kg * lb);
JOptionPane.showMessageDialog(null,sum, "Weight Conversion", JOptionPane.INFORMATION_MESSAGE);
}
}
Right now you have 2 main methods. Both of these are entry points for the program. Since they have to share information, it doesn't make sense you have both.
What I'd recommend is to change the Output's main method to a instance method, taking one parameter: the weight from the Input.
Like so:
public void printOutput(final double weight){
//...
}
You can then call that from the Input's main method like so:
public static void main(String[] args) {
String weight;
weight = JOptionPane.showInputDialog("Enter weight in kilograms");
double kg = Double.parseDouble(weight); // Be sure to parse the weight to a number
Output output = new Output(); // Create a new instance of the Output class
output.printOutput(kg); // Call our method to display the output of the conversion
}
One other thing, is that since Output is currently only used for that one method, you could consider just moving that method into Input.
// addition of two integers using JOptionPane
import javax.swing.JOptionPane;
public class Addition
{
public static void main(String[] args)
{
String firstNumber = JOptionPane.showInputDialog("Input <First Integer>");
String secondNumber = JOptionPane.showInputDialog("Input <Second Integer>");
int num1 = Integer.parseInt(firstNumber);
int num2 = Integer.parseInt(secondNumber);
int sum = num1 + num2;
JOptionPane.showMessageDialog(null, "Sum is" + sum, "Sumof two Integers", JOptionPane.PLAIN_MESSAGE);
}
}

nothing will print in the compiler. [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Here's the question I was asked:
Write a complete Java program called CalcTotalPrice. The program must include five methods:
getSaleTotal, getSalePrice, getSaleWeight, calcTax, and calcShipping.
getSaleTotal takes no input parameters and returns a double, which is the sale total, and which it computes by calling the other four methods.
getSalePrice returns a double, which it gets from the user at the command line.
getSaleWeight returns a double, which it gets from the user at the command line.
calcTax takes a double as a parameters (the sale price) and returns the tax amount as a double (use 6% as a fixed tax rate).
calcShipping takes a double as a parameter (the sale weight) and returns the shipping amount as a double (calculate shipping as $10 if weight is less than 10 and $20 if weight is 10 or greater).
getSaleTotal should print the sale price amount, tax amount, shipping amount, and sale total amount to the command line.
nothing will print in the compiler. Please help me.
Here's my code:
import java.util.Scanner;
/**
*
* #author Kramer1
*/
public class CalcTotalPrice {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
public static double getSaleTotal(){
Scanner in = new Scanner(System.in);
double price = getSalePrice(in);
System.out.println(price);
double tax = calcTax(.06);
System.out.println(tax);
double shipping = calcShipping(in.nextDouble());
System.out.println(shipping);
double saleTotal = ((price)*tax)+price+shipping;
System.out.println(saleTotal);
return saleTotal;
}
public static double getSalePrice(Scanner in){
double salePrice = in.nextDouble();
return salePrice;
}
public static double getSaleWeight(Scanner in){
double saleWeight = in.nextDouble();
return saleWeight;
}
public static double calcTax(double salePrice){
double salesTax = .06;
return salesTax;
}
public static double calcShipping(double saleWeight){
double amountShipping = 0;
if (saleWeight < 10){
amountShipping = 10.;
}else if(saleWeight > 10){
amountShipping = 20.;
}
return amountShipping;
}
}
You arent doing anything in your main()
To see the output, you will have to create the Scanner in main and then call appropriate methods.
You need to do some code refactoring. First, move your Scanner to the main method. Then pass it around as an argument to other methods to read data from or read data in main and pass the values directly. I suggest the latter
You also need to declare the variables you use outside the methods and into the class so that their values persist till the end of the program and you will have access to them in various methods. Do declare them static.
You have a main method that is empty - it is not doing anything or calling any code.
Try instantiating your class and calling some methods in it.
it also looks like it is expecting some input from the user. So also try instantiating a Scanner class in your main which can then be passed to some methods. Remember to also call in.nextLine(); to flush the input before calling the next in.nextDouble();
try
Static Double salesPrice = null;
public static void main(String[] args) {
CalcTotalPrice ctp = new CalcTotalPrice ();
Scanner sc = new Scanner(System.in);
salesPrice = ctp.getSalesPrice (in);
in.nextLine();
//etc
}

Java code what is wrong with this?

I am really new to programming, on netbeans i have deleted all the other text, all i have is the following, Why wont the program run?
The error i get is, no main Class found.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package findcost2;
public class Main
/* a program to calculate and display the cost of a product after
* sales tax has been added*/
public class FindCost2
Public static void main (String[] args)
{
double price,tax;
price = 500;
tax = 17.5;
price = price * (1 + tax/100);// calculate cost
// display results
System.out.println("***Product Price Check");
System.out.println("Cost after tax = " + price);
}
}
Try this exactly and name your java file FindCost2.java
package findcost2;
public class FindCost2{
public static void main (String[] args)
{
double price,tax;
price = 500;
tax = 17.5;
price = price * (1 + tax/100);// calculate cost
// display results
System.out.println("***Product Price Check");
System.out.println("Cost after tax = " + price);
}
}
You're missing a curly bracket after class Main and you have two public classes in the same source file. Delete public class Main and change Public to public.
You should probably also use decimal numbers for dealing with currencies
Sooner or later, everyone trying to calculate money in Java discovers that computers can't add.
Why is Public capitalized? Shoud be:
public class FindCost2 {
public static void main(String[] args) { ... }
}
Numerous problems with this code:
The outer class (Main) does not have an opening bracket. Insert the { bracket.
The inner class (FindCost2) does not have an opening bracket. Insert the { bracket.
The public modifier for the main method is capitalized. Start with a lowercase p.
The main method is nested in an inner class. This is really bad form. To make it work anyway, the inner class needs to be static. Insert the static keyword.
When put like this, it compiles:
public class Main {
/*
* a program to calculate and display the cost of a product after sales tax
* has been added
*/
public static class FindCost2 {
public static void main(String[] args) {
double price, tax;
price = 500;
tax = 17.5;
price = price * (1 + tax / 100);// calculate cost
// display results
System.out.println("***Product Price Check");
System.out.println("Cost after tax = " + price);
}
}
}
However, there is absolutely no point to the outer class (Main). Just delete this. When the outer class is removed, the inner class (FindCost2) need not be static anymore. Remove the keyword.
It is really bad form to declare multiple variables on one line (as in double price, tax;). Split that to two lines:
double price;
double tax;
There are good reasons not to use the double type for monetary values. With a little extra work, you can easily write a simple Money class. Check javapractices.com for a good overview on that.
Hope that helps!

Categories