interest rate java confusion with private static doubles [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
alright so i have already made a working compound interest rate program. but now for this program i have to re write the program using more methods. using
private static double FVCALC(..)
and
private static double validate(........)
i dont quite understand how i need to do this. the current code i have only lets me input the 3 values of interest rate and it stops. is it because of the private mehtods? im not sure what to do and i have searched for 3 days now.
bottom line is. my code is not working the way i want it to.
public class interest_rate
{
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
double i;
double n;
double FVCalc;
double PV;
System.out.print("please enter value for n (years): ");
n = input.nextInt();
System.out.print("please enter interest rate: ");
i=input.nextDouble();
System.out.print("please enter Present Value: ");
PV = input.nextDouble();
}
private static double validate (double upLimit, double lowLimit, double PV)
{
upLimit=100000.00;
lowLimit=0.00;
while(PV>upLimit|| PV<lowLimit)
{
System.out.print("please enter value between "+upLimit+" and "+lowLimit);
System.out.print("please enter PV");
PV=input.nextDouble();
}
return PV;
}
private static double FVCalc(double PV, double i, double n, double FV)
{
FV = PV*Math.pow(1+(i/100), n);
return(FV);
}
}

First, you need to call the methods in main.
Secondly, you cant pass in PV, then reassign it and expect the value to update.
For example..
private static double validate (double upLimit, double lowLimit, double PV)
You need to call this in main like so
PV = 0.0; // some double value
double validated = validate(0,100000); // return the value, don't pass it in
And remove these lines in that method because overriding parameters is typically bad.
upLimit=100000.00;
lowLimit=0.00;
Next, add a field for your values that you want to use throughout the class.
public class InterestRate
{
static double pv , fvCalc;
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
}
And remove these lines in main and use those two class variables instead
double FVCalc;
double PV;
Additionally, I don't see a reason to store fvCalc as a variable. You can just calculate it
private static double fvCalc(double pV, double i, double n)
{
return pV*Math.pow(1+(i/100), n);
}

i believe i have figured it out. and i made it pretty. excuse the notes. i wanted to keep them there to see what i did wrong. thanks all.
public class interest_rate
{
static double pV , fvCalc, i, n;
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
double validated;
double calculated;
double i;
double n;
//double fV;
//double pV1;
System.out.print("please enter value for n (years): ");
n = input.nextInt();
System.out.print("please enter interest rate: ");
i=input.nextDouble();
validated = validate(0,100000);
System.out.println("pV is validated and equal to: "+validated);
calculated= fvCalc(validated,i,n);
System.out.println("your calulation for interest is: "+calculated);
}
private static double validate(double upLimit, double lowLimit) {
double pV;
System.out.print("please enter pV");
pV=input.nextDouble();
while(pV<upLimit|| pV>lowLimit)
{
System.out.print("please enter value between "+upLimit+" and "+lowLimit);
System.out.println("please enter pV");
pV=input.nextDouble();
}
return pV;
}
private static double fvCalc(double pV, double i, double n)
{
double fV;
fV=pV*Math.pow(1+(i/100), n);
return fV;
}
}

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.

Comparing return values from two overloaded methods in an if statement (in main method)

So i'm new to java, we just started this language in my programming class about a month ago. Anyhow, we're on overloading methods right now (just started methods last week) and I'm having trouble with comparing the values of the return statements in the overloaded methods. My intention is to compare them in an if statement in the main method. I'm sure the answer is simple, but i can't find information on it in my textbook or online. Sorry about the sloppy indentation, I'm having trouble with the features on this website and it's the first time i've used it. would appreciate any help! Here is the program:
import java.util.Scanner;
public class pizzaCalculation {
public static void main(String[] args){
//create scanner
Scanner i = new Scanner(System.in);
//create sentinel while loop, initiate priceperinch for both pizzas
int sentinel = 1;
//create while loop
while(sentinel != 0){
//create input for round pizza
System.out.println("What is the price of the round pizza?");
double priceRound = i.nextDouble();
System.out.println("What is the radius?");
double radius = i.nextDouble();
pizzaPrice(radius, priceRound);
System.out.println("What is the price of the rectangular pizza?");
double priceRect = i.nextDouble();
System.out.println("What is the width and length of the rectangular pizza?");
double width = i.nextDouble();
double length = i.nextDouble();
pizzaPrice();
//create if statement to determine best deal
if (pricePerInchRound > pricePerInchRect){
System.out.println("The best deal is the round pizza which is $"+pricePerInchRound);
}else{
System.out.println("The best deal is the rectangular pizza is $"+pricePerInchRect);
}
//ask if user would like to do again
System.out.println("Would you like to do another calculation? Enter 1 for yes and 0 for no.");
sentinel = i.nextInt();
}
}
public static double pizzaPrice(double num1, double priceRound){
Scanner i = new Scanner(System.in);
//this is for round pizza
double areaRound = Math.PI * num1 * num1;
double pricePerInchRound = priceRound / areaRound;
return pricePerInchRound;
}
public static double pizzaPrice(double num1, double num2, double priceRect){
//this is for rectangular pizza
//create scanner
Scanner i = new Scanner(System.in);
double areaRect = num1 * num2;
double pricePerInchRect = priceRect / areaRect;
return pricePerInchRect;
}
}
So there are several issues:
You need to pass parameters to the second call of pizzaPrice() like this
pizzaPrice(width, length, priceRect);
You need to store results of method calls in variables like
pricePerInchRound = pizzaPrice(a, b);
pricePerInchRect = pizzaPrice(a, b, c);
You are calling pizzaPrice() but you need to store the resulting value in a variable so you can use it later (and pass the right parameters).
double pricePerInchRound = pizzaPrice(radius, priceRound);
and ...
double pricePerInchRect = pizzaPrice(width, length, priceRect);
Also, take care to name your method parameters better - num1, num2 aren't very descriptive. You could have used width, length.

Java code is not allowing my variable to be used

When I try to run this code, it won't let me use "bmi". I'm trying to make a simple Body Mass Index calculator, but I don't understand why it won't work. If you could rewrite the code properly, it'd help me learn better.
import java.util.Scanner;
public class Bmi {
int weight;
int height;
int bmi = weight /(height*height) * 703;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter weight: ");
int weight = input.nextInt();
System.out.print("Enter height: ");
int height = input.nextInt();
System.out.println(bmi);
}
}
You are trying to use non static members inside static context.
You don't really need any instance/static variables here. Just go with local variables.
import java.util.Scanner;
public class Bmi {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter weight: ");
int weight = input.nextInt();
System.out.print("Enter height: ");
int height = input.nextInt();
int bmi = weight /(height*height) * 703;
System.out.println(bmi);
}
}
Although it is not happen in real world, when your height is greater than weight you end up in zero as integer division is happening. Better you change them to doubles. Give a read Why is the result of 1/3 == 0?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter weight: ");
double weight = input.nextInt();
System.out.print("Enter height: ");
double height = input.nextInt();
double bmi = weight / (height * height) * 703;
System.out.println(bmi);
}
Finally
int bmi = weight /(height*height) * 703;
That statement won't keep a track on values of weight and height. You need to reevaluate each time when they change.
You should never combine the worker and user code in a same class.
Better to create a separate class for calculator say BmiCalculator and define a static method to calculate bmi say calculateBmi. Static because its just dependent on the input it needs and nothing else.
Then call and use this static method directly in your CallerClass
Please refer the below code:
import java.util.Scanner;
class BmiCalculator {
public static double calculateBmi(double weight, double height){
return weight /(height*height) * 703;
}
}
public class CallerClass{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter weight: ");
double weight = input.nextInt();
System.out.print("Enter height: ");
double height = input.nextInt();
System.out.println(BmiCalculator.calculateBmi(weight,height));
}
}
It's because you trying to access instance context from static context. Simpliest way to fix this is add static modificator to your
fields and remove bmi calculation from bmi field assignment because all static is initialized when class loaded. More concise
way to write this code is that:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter weight: ");
int weight = input.nextInt();
System.out.print("Enter height: ");
int height = input.nextInt();
Bmi bmi = new Bmi(weight, height); //create new bmi instance
System.out.println(bmi.value()); // get it's value
System.out.println(bmi); // calls toString() method (object text representation)
//that we already override in Bmi class
}
}
We decouple Bmi calculation from user input with way to create separate class, now Bmi class knows nothing about user input and it's good because in this way we increased cohesion and reduce coupling in Main and Bmi classes.
It helps to code reuse in different projects and ease mantain efforts. See https://en.wikipedia.org/wiki/GRASP_(object-oriented_design) for more information.
public class Bmi { //place to separate file with name Bmi.java
private int weight;
private int height;
public Bmi(int weight, int height) {
this.weight = weight;
this.height = height;
}
/**
returns a bmi value
*/
public int value() {
return weight / (height * height) * 703;
}
public String toString() {
return value();
}
}

How do I do calculations in a separate method then send them back to main for printing?

I am trying to do the calculations for the interest in another method, and I know that I have to make another method outside of main and then put return an the end, but I have no idea what to title this new method and how to go about doing the calculations there. I think it is the while loop that is confusing me. I have done this once before on a different project, so I have an idea of how to do it, but this project isn't anything like the other one and I don't really understand it. Any help is extremely appreciated as I have been working on this for a long time and just want to get it over with. Thanks in advance.
import java.util.Scanner; // This allows for the use of the scanner in the class
public class SavingsAccount // Start of class
{
public static void main(String[]args) // Start of main
{
double P; // These store the amounts that will be used in the accruing interest formula
double i;
double n;
double S = 0;
int timesLooped = 0;
Scanner readConsole = new Scanner(System.in); // This is the scanner
System.out.println("I am a savings account interest calculator."); // Prompts the user for input
System.out.println("How much money have you deposited?");
P = readConsole.nextDouble();
S = P;
System.out.println("Now, what is the annual interest rate? (i.e. .05)");
i = readConsole.nextDouble();
System.out.println("Finally, how long do you plan on having the money in the account?");
n = readConsole.nextDouble();
while (timesLooped <= n)
{
S = S + (P * i);
timesLooped += 1;
}
System.out.println("Your balance in that time span is " + S + "."); // Tells you your ending balance
}
}
Based on your comment, I think you want this:
private static double addInterest(double S, double P, double i)
{
return S + (P * i);
}
...
public static void main()
{
...
while (timesLooped <= n)
{
S = addInterest(S, P, i);
}
EDIT
I made some small improvements just for fun:
I put the entire interest calculation into the function and used exponentiation rather than a loop.
I gave the variables more descriptive names.
I used System.out.format to print the result.
Here's the code:
private static double computeCompoundInterest(double principal, double rate,
double years) {
return principal * Math.pow(1 + rate, years);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("I am a savings account interest calculator.");
System.out.println("How much money have you deposited?");
double principal = scanner.nextDouble();
System.out.println("Now, what is the annual interest rate? (i.e. .05)");
double rate = scanner.nextDouble();
System.out.println("How many years will you hold that money in the account?");
double years = scanner.nextDouble();
double total = computeCompoundInterest(principal, rate, years);
System.out.format("Your balance at the end of that period will be %.2f.\n", years, total);
}

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;
}
}
}

Categories

Resources