Java Method isn't implementing what it is supposed to - java

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.

Related

How do we use a variable from one method to another for eg im trying divide one variable by another

I'm trying to divide variables from pointsearned and creditsearned method in the pointsaverage method but it gives "Your grade point average isNaN" when i run it , how do i fix this ?(I'm a beginner)
public class JavaApplication40 {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
double credits = 0;
double Points = 0;
double average = 0;
IDnumber();
CreditsEarned(credits);
PointsEarned(Points);
System.out.println("Your grade point average is" + PointAverag(average, Points, credits));
}
public static void IDnumber(){
String docNuMBER;
System.out.println("Enter your student ID number ");
docNuMBER = keyboard.nextLine();
}
public static double CreditsEarned( double credits){
double NumCreditsEarned;
System.out.println("Enter your Credit hours earned");
NumCreditsEarned = keyboard.nextDouble();
return NumCreditsEarned;
}
public static double PointsEarned(double points){
double NumberOpoints;
System.out.println("Enter your credit points");
NumberOpoints = keyboard.nextDouble();
return NumberOpoints;
}
public static double PointAverag(double grade , double NumberOpoints ,
double NumCreditsEarned) {
double average ;
average = NumberOpoints/NumberOpoints;
return average ;
Here's what's happening in your program:
You set 'credits' and 'points' to 0.
These two variables have not been modified when you get to pass them to 'pointAverag'
System.out.println("Your grade point average is" + PointAverag(average, Points, credits));
this line, literally, does this:
System.out.println("Your grade point average is" + PointAverag(0, 0, 0));
And eventually leads to:
average = 0/0
in 'PointAverag' which is NAN when stored in a double.
Watch out for this line:
average = NumberOpoints/NumberOpoints;
it has logical mistake in it. It will always store either 1 or NAN.
As mentionned in the comments, you need to update those variables, 'credits' and 'points', by storing the returned value of your methods 'PointsEarned' and 'CreditsEarned' in them:
CreditsEarned(credits);
PointsEarned(Points);
Becomes
credits = CreditsEarned(credits);
points = PointsEarned(Points);
Hope this helps.
Write:
System.out.println("Your grade point average is" + PointAverag(IDnumber(), PointsEarned(Points), CreditsEarned(credits)));
instead.
If you don't use a returned value, it gets discarded.

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.

interest rate java confusion with private static doubles [closed]

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

Cant seem to get my scanner working

import java.util.*;
import java.util.Scanner;
import java.io.*;
class Point
{
/* Method to find the quadrant of both the points p and q*/
public String quadrant(double xp, double yp, double xq, double yq){
Scanner keyboard= new Scanner(System.in);
System.out.print("Enter the first value for Xp: ");
xp = keyboard.nextDouble();
Scanner keyboard1 = new Scanner(System.in);
System.out.print("Enter the first value for Yp: ");
yp = keyboard.nextDouble();
Scanner keyboard2= new Scanner(System.in);
System.out.print("Enter the first value for Xq: ");
xq = keyboard.nextDouble();
Scanner keyboard3= new Scanner(System.in);
System.out.print("Enter the first value for Yq: ");
yq = keyboard.nextDouble();
String p_quadrant=getQuadrant(xp,yp);
String q_quadrant=getQuadrant(xq,yq);
return "Point p is at "+p_quadrant+" and Point q is at "+q_quadrant;
}
/* Method to get the quadrant of each passed point*/
public String getQuadrant(double x, double y){
if(x==0 && y==0){
return "Origin";
}
else if(x==0){
return "Y-axis";
}
else if(y==0){
return "X-axis";
}
if (x >= 0) {
return (y >= 0 ? "1st Quadrant":"4th Quadrant");
} else {
return (y >= 0 ? "2nd Quadrant":"3rd Quadrant");
}
}
/* Method to get the euclidean distance between p and q */
public double euclidean(double xp, double yp, double xq, double yq){
double euc_distance = 0.0;
double x_square=Math.pow((xq-xp), 2);
double y_square=Math.pow((yq-yp), 2);
euc_distance= Math.sqrt(x_square+y_square);
return euc_distance;
}
/* Method to calculate the slope */
public double slope(double xp, double yp, double xq, double yq){
double x_diff= xp-xq;
double slope=0.0;
/* Check applied to avoid a divide by zero error */
if(x_diff == 0){
System.out.println("Slope is undefined");
System.exit(1);
}
else{
slope=(yp-yq)/x_diff;
}
return slope;
}
public static void main (String[] args) throws java.lang.Exception
{
/* Creating an object of Points and calling each method individually and printing the value*/
Points p = new Points();
double euc=p.euclidean(2.3, 5.6,0.5,9);
String quad=p.quadrant(0, -5.6,0,0);
double slop=p.slope(0,0.5,0.6,9);
System.out.print("Euclidean:"+euc+"\n Quadrant:"+quad+"\n Slope:"+slop);
}
}
I can't figure out why my scanner isn't working; I'm not getting errors either. My job is to ask the user for INPUTS for all the points. Really I am stuck and this is due in a few hours, and also I'm using the latest eclipse with new JDK. New to programming and this site XD.
When I run the program my I get this as a result; I'm not getting any errors either
Euclidean:3.847076812334269
Quadrant:Point p is at Y-axis and Point q is at Origin
Slope:14.166666666666668
You need to update your prompts and get rid of unnecessary Scanners to fix the problem. Your prompts all ask for the "first" value, and keyboard1 -keyboard3 are never used. This code works just as well:
Scanner keyboard= new Scanner(System.in);
System.out.print("Enter the first value for Xp: ");
xp = keyboard.nextDouble();
System.out.print("Enter the first value for Yp: ");
yp = keyboard.nextDouble();
System.out.print("Enter the first value for Xq: ");
xq = keyboard.nextDouble();
System.out.print("Enter the first value for Yq: ");
yq = keyboard.nextDouble();
String p_quadrant=getQuadrant(xp,yp);
String q_quadrant=getQuadrant(xq,yq);
return "Point p is at "+p_quadrant+" and Point q is at "+q_quadrant;
}
Also, in your main method, instead of creating a Point() object you create a Points() object. It does give me an error.

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