(HackerRank Day 2: Operators) Problem with Constructor - java

In this HackerRank challenge, I need to find the total meal cost by adding tip_percent which is 20% of the meal_cost and tax_percent which is 8% of the meal_cost and the meal_cost being $12. So the output must be a round number of 15 but my output comes out as $14.
It does seem to work properly with custom values like $12.50 for meal_cost which later totaled comes out as a rounded value of $16. What am I doing wrong here?
static double findMealTotal(double meal_cost, int tip_percent, int tax_percent) {
tip_percent = (int)(meal_cost * tip_percent)/100;
tax_percent = (int)(meal_cost * tax_percent)/100;
return meal_cost + tip_percent + tax_percent;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
double meal_cost = scanner.nextDouble();
int tip_percent = scanner.nextInt();
int tax_percent = scanner.nextInt();
//changed solve to mealTotal
double mealTotal = findMealTotal(meal_cost, tip_percent, tax_percent);
System.out.println(Math.round(mealTotal));
scanner.close();
}

You are using integers. Integers are rounded, so you loose precision over the next calculation. Try using doubles and cast to int at the end.
static void Main(string[] args)
{
double cost = findMealTotal(12, 20, 8);
Console.WriteLine(cost.ToString());
}
static double findMealTotal(double meal_cost, int tip_percent, int tax_percent)
{
double tip = meal_cost * tip_percent / 100;
double tax = meal_cost * tax_percent / 100;
return meal_cost + tip + tax;
}
And don't reuse parameters inside your function. It is bad practice.

Related

Returning a value from one method to another to be used in the output

I can't figure out how to return the value of finalCost to the main method and have it printed.
import java.util.*;
public class PhonePlan {
private static double basecost = 8.5;
private static double rate = 0.35;
private static double discount = 0.15;
public static void main(String[] args) {
//Scan input for downloadLimit
Scanner scan = new Scanner(System.in);
System.out.print("Enter the download limit in GB: ");
int downloadLimit = scan.nextInt();
// Call other method
calcMonthlyCharge(downloadLimit);
System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost));
}
public static double calcMonthlyCharge(double downloadLimit) {
// Calculate final cost
double fullCost = downloadLimit * rate + basecost;
double planDiscount = fullCost * discount;
double finalCost = fullCost - planDiscount;
return finalCost;
}
}
Specifically, I can't find how to use the returned value in the "println" line.
System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost) );
}
public static double calcMonthlyCharge(double downloadLimit) {
// Calculate final cost
double fullCost = downloadLimit * rate + basecost;
double planDiscount = fullCost * discount;
double finalCost = fullCost - planDiscount;
return finalCost;
}
You call calcMonthlyCharge(downloadLimit),but don't store the returnvalue.
When you call System.out.println("Plan monthly cost: " + calcMonthlyCharge(finalCost) );
It is unknown what finalcost is, this is a variable which only exist in the scope of calcMonthlyCharge
Either store the returnvalue of calcMonthlyCharge(downloadLimit) and reuse the value to print, or use calcMonthlyCharge(downloadLimit) in your println with downloadLimit as parameter to get a new returnvalue.

Java netbeans issue

Please help me with this netbeans assignment code. I have been working on it for a few hours, and I don’t understand it.
Thanks!
I would avoid using raw user input for now, and just focus on creating a reusable method that does your calculation internally. There is no reason to cast to a float, because all the values should be floating-point values.
The calc method handles the calculation that you have copy-pasted three times.
public class CalculateHalfLife {
public static double calc(double amount, double halfLife, double hours) {
return amount / (Math.pow(2, (hours / halfLife)));
}
public static void main(String[] args) {
double amount = 100; // mg of caffeine
double halfLife = 6; // hours
double[] allHours = { 6, 12, 24 };
for (double hours : allHours) {
double output = calc(amount, halfLife, hours);
System.out.printf("After %.0f hours: %.2f mg\n", hours, output);
}
}
}
If you want to to support user input, you should prompt the user to enter input:
import java.util.Scanner;
public class CalculateHalfLife {
private static double amount = 100; // mg of caffeine
private static double halfLife = 6; // hours
private static double[] allHours = { 6, 12, 24 };
public static double calc(double amount, double halfLife, double hours) {
return amount / (Math.pow(2, (hours / halfLife)));
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an amount: ");
float amount = sc.nextFloat();
System.out.println();
for (double hours : allHours) {
double output = calc(amount, halfLife, hours);
System.out.printf("After %.0f hours: %.2f mg\n", hours, output);
}
sc.close();
}
}

Basic Java, passing data between methods

I am new to Java and trying to make a basic body mass calculator.
My problem is I need to ask the questions, convert the measurements and then pass it to another method then display the results in a separate method.
I've added my code below but keep getting a 1.0 returned as the answer each time.
import java.util.Scanner;
public class calcBMI {
public static void main(String[] args)
{
Scanner keyboard = new Scanner( System.in );
System.out.print("Enter weight in pounds: ");
double weightInPounds = keyboard.nextDouble();
double weightInKg = (weightInPounds / 2.2);
System.out.print("Enter height in inches: ");
double heightInInches = keyboard.nextDouble();
double heightInMeters = (heightInInches / 0.254);
double resultBMI = 1;
displayResults(resultBMI);
}
public static double bodyMassIndex(double weightInKg, double
heightInMeters)
{
double resultBMI = weightInKg / Math.pow(heightInMeters, 2) * 1.375;
return resultBMI;
}
public static void displayResults(double resultBMI)
{
System.out.printf("The calculated body mass index was: " + resultBMI);
System.out.println();
}
}
Updated code, now getting;
Enter weight in pounds: 180
Enter height in inches: 68
The calculated body mass index was: 1.1415618118905313E-5
BUILD SUCCESSFUL (total time: 3 seconds)
import java.util.Scanner;
public class calcBMI {
public static void main(String[] args)
{
Scanner keyboard = new Scanner( System.in );
System.out.print("Enter weight in pounds: ");
double weightInPounds = keyboard.nextDouble();
double weightInKg = (weightInPounds / 2.2);
System.out.print("Enter height in inches: ");
double heightInInches = keyboard.nextDouble();
double heightInMeters = (heightInInches / 0.0254);
displayResults(bodyMassIndex(weightInKg, heightInMeters));
}
public static double bodyMassIndex(double weightInKg, double heightInMeters)
{
return (weightInKg / Math.pow(heightInMeters, 2));
}
public static void displayResults(double resultBMI)
{
System.out.printf("The calculated body mass index was: " + resultBMI);
System.out.println();
}
}
You are not calling the bodyMassIndex method in your code at all. Change
displayResults(resultBMI);
to
displayResults(bodyMassIndex(weightInKg, heightInMeters));
resultBMI equals 1, so of course the output would always be :
"The calculated body mass index was: 1"
Full code:
public static void main(String[] args) {
System.out.print("Enter weight in pounds: ");
double weightInPounds = keyboard.nextDouble();
double weightInKg = (weightInPounds / 2.2);
System.out.print("Enter height in inches: ");
double heightInInches = keyboard.nextDouble();
double heightInMeters = (heightInInches / 0.254);
// You can get rid of the resultBMI variable
displayResults(bodyMassIndex(weightInKg, heightInMeters));
}
You get 1.0 because you hard coded it as such.
Change this:
double resultBMI = 1;
To:
double resultBMI = bodyMassIndex(weightInKG, heightInMeters);
By the way, you could also have returned BMI directly in the method and there is no need to multiply by 1.375 anymore since you are already supplying weight in KG:
public static double bodyMassIndex(double weightInKg, double heightInMeters)
{
return (weightInKg / (heightInMeters*heightInMeters));
}
Add on:
Your conversion from inches to meters is wrong as well. It should be:
double heightInMeters = (heightInInches * 0.0254);

Cannot find symbol in return statement and average issue

I'm having two issues in this code where I'm getting and a lossy conversion error
for double to int. No idea how to approach that. (code directly below following lines)
and My average or mean finder keeps giving me incorrect answers when I input numbers with decimals. Any help would be greatly appreciated.
public static double findMaxNumber(double maxNumber, double [] profit) {
double theLowestValue = profit[maxNumber];
import java.util.Arrays;
import java.util.Scanner;
class Business
{
public static void main(String[] args) {
Scanner inputScanner;
inputScanner = new Scanner (System.in);
System.out.println("Welcome to the profit-calculation program.");
System.out.println("how many days of data do you have?");
int n = Integer.parseInt (inputScanner.nextLine());
//call upon a function to store the profits into an array for further use.
double[] dayProfitList = inputProfit(n);
//call upon a function to calculate average profit
double averageValue = calcAverageProfit(dayProfitList);
System.out.println("the average of these values is " +calcAverageProfit(dayProfitList) + "."); //print out devised average
//call upon a function to calculate standard devation
double standardDeviation = calcStandardDeviation(averageValue, dayProfitList);
System.out.println("the standard deviation is plus or minus " +calcStandardDeviation(averageValue, dayProfitList));
//find the most profitable day
double theMax = findMax(dayProfitList);
System.out.println("the most profitable day was " + findMax(dayProfitList));
findMaxNumber(theMax, dayProfitList);
System.out.println("and the value earned that day was " + findMaxNumber(theMax, dayProfitList));
findLeast(dayProfitList);
System.out.println("the least profitiable day was " + findLeast(dayProfitList));
}
//function to store each days profits within an array
public static double[] inputProfit(int days) {
Scanner inputScanner;
inputScanner = new Scanner (System.in);
System.out.println("input the profit on..");
double[] profits = new double [days+1];
for(int i = 1; i<days + 1; i++) {
System.out.println("day " + i + "?");
double storedDays = Double.parseDouble (inputScanner.nextLine());
profits[i] = storedDays;
}
return profits;
}
//fuction to calculate the profit of said days.
public static double calcAverageProfit(double [] profit){
double sum = 0;
double average = 0;
for(int i = 1; i<profit.length; i++){
sum = profit[i] + sum;
}
average = sum/profit.length;
return average;
}
public static double calcStandardDeviation(double average, double[] profit){
double stepThree = 0;
double sum = 0;
double product = 0;
for(int i = 1;i<profit.length; i++) {
sum = profit[i] - average;
product = sum * sum;
stepThree = product + stepThree;
}
double standardDeviation = stepThree/profit.length;
java.lang.Math.sqrt(standardDeviation);
return standardDeviation;
}
public static double findLeast(double [] profit){
double least = profit[0];
for (int i = 1; i<profit.length; i++) {
if (profit[i]>least)
least = profit[i]; }
return least;
}
public static double findMaxNumber(double maxNumber, double [] profit) {
int MaxNumberInt = (int) maxNumber;
double theLowestValue = profit[maxNumber];
return theLowestValue; }
For fix double to int conversion error, you have to change your code as below.
from
double theLowestValue = profit[maxNumber];
to
double theLowestValue = profit[MaxNumberInt];
After changed, it should below as below.
public static double findMaxNumber(double maxNumber, double[] profit) {
int MaxNumberInt = (int) maxNumber;
double theLowestValue = profit[MaxNumberInt];
return theLowestValue;
}
In your average/mean finder iterate profit[] array from 0th index.
public static double calcAverageProfit(double [] profit) {
...
for (int i = 0; i < profit.length; i++) {
...
}
}

call method with parameters java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I looked and could not find anything like what I am wanting to do. I have a method with 3 parameters that I need to call from my main method. I've tried everything I have leaned in class so far, but I cannot fig this out. this is for my Programming in Java Course. Here is what I need to call from my main method:
import java.util.*;// for scanner
import java.text.DecimalFormat;
public class Grades {
//Homework, exam1, and exam2 weights
static double homeworkWeight;
static double examOneWeight;
static double examTwoWeight;
//Homework
static int homeworkNumberOfAssignments;
static int homeworkAssignment1Score;
static int homeworkAssignment1Max;
static int homeworkAssignment2Score;
static int homeworkAssignment2Max;
static int homeworkAssignment3Score;
static int homeworkAssignment3Max;
static int homeworkSectionsAttended;
static int homeworkSectionsAttendedTotal;
static int homeworkSectionsAttendedMax;
double homeworkTotalPoints;
double homeworkMaxPoints;
double homeworkWeightedScore;
//Exam1
static int examOneScore;
static int examOneCurve;
static double examOneMaxPointsAvailable;
double examOneWeightedScore;
//Exam2
static int examTwoScore;
static int examTwoCurve;
static double examTwoMaxPointsAvailable;
double examTwoWeightedScore;
//Grades
static double courseGrade;
static double grade;
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
showIntro();
System.out.println("");
System.out.print("Homework and Exam 1 weights? ");
homeworkWeight = console.nextInt();
examOneWeight = console.nextInt();
examTwoWeight = 100 - homeworkWeight + examOneWeight;
System.out.println("Using weights of " + homeworkWeight + " " + examOneWeight + " " + examTwoWeight);
homework();
System.out.println("");
exam1();
//System.out.println("");
//exam2();
//System.out.println("");
//courseGrade(courseGrade; double homeworkWeightedScore; double examOneWeightedScore; double examTwoWeightedScore;);
double d = courseGrade(homeworkWeightedScore, examTwoWeightedScore, examTwoWeightedScore);
System.out.println("");
}//
//Shows the intro to the program to the user.
public static void showIntro() {
System.out.println("This program accepts your homework scores and");
System.out.println("scores from two exams as input and computes");
System.out.println("your grades in the course.");
}
public static void homework() {
Scanner console = new Scanner(System.in);
System.out.println("");
System.out.println("Homework:");
System.out.print("Number of assignments? ");
homeworkNumberOfAssignments = console.nextInt();
System.out.print("Assignment 1 score and max? ");
homeworkAssignment1Score = console.nextInt();
homeworkAssignment1Max = console.nextInt();
System.out.print("Assignment 2 score and max? ");
homeworkAssignment2Score = console.nextInt();
homeworkAssignment2Max = console.nextInt();
System.out.print("Assignment 3 score and max? ");
homeworkAssignment3Score = console.nextInt();
homeworkAssignment3Max = console.nextInt();
System.out.print("Sections attended? ");
homeworkSectionsAttended = console.nextInt();
homeworkSectionsAttendedTotal = homeworkSectionsAttended * 4;
homeworkSectionsAttendedMax = 20;
//Calculating total points earned
double totalPoints = homeworkAssignment1Score + homeworkAssignment2Score + homeworkAssignment3Score + homeworkSectionsAttendedTotal;
//Calutaing the max points available to be earned
double maxPoints = homeworkAssignment1Max + homeworkAssignment2Max + homeworkAssignment3Max + homeworkSectionsAttendedMax;
//Formatting with DecimalFormat to remove the decimal and 0 when displaying
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(("Total points = ") + df.format(totalPoints) + " / " + df.format(maxPoints));
//Calculating the weighted score by dividing totalPoints by maxPoints and then multiplying times homeworkWeight
double homeworkWeightedScore = ((totalPoints / maxPoints) * homeworkWeight);
//Printing out weighted score and rounding to the nearest hundreth with Math.round
System.out.println("Weighted score = " + Math.round(homeworkWeightedScore * 100.0) / 100.0);
}
public static void exam1() {
Scanner console = new Scanner(System.in);
System.out.println("Exam 1:");
System.out.print("Score? ");
examOneScore = console.nextInt();
System.out.print("Curve? ");
examOneCurve = console.nextInt();
System.out.println("Total points = " + examOneScore + " / " + examOneCurve);
examOneMaxPointsAvailable = 100;
double examOneWeightedScore = ((examOneScore / examOneMaxPointsAvailable) * examOneWeight);
System.out.println("weighted score = " + Math.round(examOneWeightedScore * 100.0) / 100.0);
}
public static void exam2() {
Scanner console = new Scanner(System.in);
System.out.print("Exam 2:");
System.out.print("Score? ");
examTwoScore = console.nextInt();
System.out.print("Curve? ");
examTwoCurve = console.nextInt();
System.out.print("Total points = ");
System.out.println("weighted score = ");
}
public double courseGrade(double homeworkWeightedScore, double examOneWeightedScore, double examTwoWeightedScore) {
return homeworkWeightedScore + examOneWeightedScore + examTwoWeightedScore;
}
}
There's a couple factors missing from your question that makes me unable to completely answer them, but:
Is the courseGrade method in a separate class or in the same class as your public static void main method?
Yes: Create a new instance of the separate class by doing: public SeparateClass instance = new SeparateClass(); inside of public static void main
After that, call this from your main method: double grade = instance.courseGrade(homeworkWeightedScore, examTwoWeightedScore, examTwoWeightedScore);
No: Make the courseGrade method static, you can't call a non-static method from a static method (replace public double courseGrade with public static double courseGrade). After that, inside of your main method, do this: double d = courseGrade(homeworkWeightedScore, examTwoWeightedScore, examTwoWeightedScore);
I hope this helps.

Categories