Basic Java, passing data between methods - java

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

Related

(HackerRank Day 2: Operators) Problem with Constructor

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.

2 method Exception in thread "main" java.util.NoSuchElementException

I keep getting the Exception in thread "main" java.util.NoSuchElementException error message. I have tried switching stuff around, but I keep having this problem
I have tried declaring the variables in different methods, but nothing is seeming to work.
import java.util.Scanner;
public class LabProgram {
public static double drivingCost(double drivenMiles, double milesPerGallon, double dollarsPerGallon) {
double totalCost = (drivenMiles / milesPerGallon) * dollarsPerGallon;
return totalCost;
}
public static void main(String[] args) {
double milesG;
double dollarsG;
Scanner scnr = new Scanner(System.in);
milesG = scnr.nextDouble();
dollarsG = scnr.nextDouble();
drivingCost(10.0, milesG, dollarsG);
milesG = scnr.nextDouble();
dollarsG = scnr.nextDouble();
drivingCost(50.0, milesG, dollarsG);
milesG = scnr.nextDouble();
dollarsG = scnr.nextDouble();
drivingCost(400.0, milesG, dollarsG);
}
}
The problem is:
Write a method drivingCost() with input parameters drivenMiles, milesPerGallon, and dollarsPerGallon, that returns the dollar cost to drive those miles. All items are of type double. If the method is called with 50 20.0 3.1599, the method returns 7.89975.
Define that method in a program whose inputs are the car's miles/gallon and the gas dollars/gallon (both doubles). Output the gas cost for 10 miles, 50 miles, and 400 miles, by calling your drivingCost() method three times.
Output each floating-point value with two digits after the decimal point.
The input is: 20.0 3.1599
Expected output: 1.58 7.90 63.20
import java.util.Scanner;
public class LabProgram {
/* Define your method here */
public static double drivingCost(double drivenMiles, double milesPerGallon, double dollarsPerGallon) {
double totalCost = (dollarsPerGallon * drivenMiles / milesPerGallon);
return totalCost;
}
public static void main(String[] args) {
/* Type your code here. */
Scanner scnr = new Scanner(System.in);
double milesPerGallon = scnr.nextDouble();
double dollarsPerGallon = scnr.nextDouble();
double drivenMiles = 1;
System.out.printf("%.2f ", drivingCost(drivenMiles, milesPerGallon, dollarsPerGallon) * 10);
System.out.printf("%.2f ", drivingCost(drivenMiles, milesPerGallon, dollarsPerGallon) * 50);
System.out.printf("%.2f\n", drivingCost(drivenMiles, milesPerGallon, dollarsPerGallon) * 400);
}
}
drivenMiles divided by milesPerGallon then multiplying by dollarsPerGallon will give you the price of gas per mile driven.
Note: drivenMiles just needs to be passed to drivingCost in this case. That is why the integers 10, 50 and 400 are added to call.
since drivingCost has the parameters milesPerGallon, dollarsPerGallon and drivenMiles in that order, you have to call the method with the same order of the parameters.
"%.2f" will get two decimals to the right. Adding \n will start a new line afterward.
import java.util.Scanner;
public class LabProgram {
public static double drivingCost(double milesPerGallon, double dollarsPerGallon, double drivenMiles) {
// calcuating the cost of gas
double totalCost = (drivenMiles / milesPerGallon) * dollarsPerGallon;
return totalCost;
}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double milesPerGallon;
double dollarsPerGallon;
milesPerGallon = scnr.nextDouble();
dollarsPerGallon = scnr.nextDouble();
// order of the call to the method is important, printing cost of gas for 10, 50, and 400 miles
System.out.printf("%.2f ",drivingCost(milesPerGallon, dollarsPerGallon, 10));
System.out.printf("%.2f ",drivingCost(milesPerGallon, dollarsPerGallon, 50));
System.out.printf("%.2f\n",drivingCost(milesPerGallon, dollarsPerGallon, 400));
}
}
You are calling scnr.nextDouble(); six times in your main function. Make sure you provide six arguments of type double when running your program. Currently, you are passing less that six arguments and scnr.nextDouble(); is throwing the exception as it could not find the next argument of type double.
import java.util.Scanner;
public class LabProgram {
public static double drivingCost(double milesPerGallon, double dollarsPerGallon, double drivenMiles) {
return (drivenMiles / milesPerGallon) * dollarsPerGallon;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double milesPerGallon, dollarsPerGallon;
milesPerGallon = input.nextDouble();
dollarsPerGallon = input.nextDouble();
System.out.printf("%.2f ", drivingCost(milesPerGallon, dollarsPerGallon, 10));
System.out.printf("%.2f ", drivingCost(milesPerGallon, dollarsPerGallon, 50));
System.out.printf("%.2f\n", drivingCost(milesPerGallon, dollarsPerGallon, 400));
}
}

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.

Why is nothing happening when I run my program?

When I execute my program the console is completely empty. I have no idea what is causing this to happen. I am not receiving any error messages except for the "scanner not closed" warning. What is causing this issue?
public class BMIprogram {
public static void main(String[] args) {
double BMI;
double weight;
double height;
Scanner bodymassScan = new Scanner(System.in);
weight = bodymassScan.nextInt();
height = bodymassScan.nextInt();
System.out.println("Enter weight in pounds: ");
System.out.println("Enter height in inches: ");
BMI = ((weight/Math.pow(height, 2)) * 703);
System.out.println(BMI + " is the BMI");
}
}
Just rearrange your code! The Scanner is waiting for you to make two inputs before printing out the statements.
public class BMIprogram {
public static void main(String[] args) {
double BMI;
double weight;
double height;
Scanner bodymassScan = new Scanner(System.in);
System.out.println("Enter weight in pounds: ");
weight = bodymassScan.nextInt();
System.out.println("Enter height in inches: ");
height = bodymassScan.nextInt();
BMI = ((weight/Math.pow(height, 2)) * 703);
System.out.println(BMI + " is the BMI");
}
}
You can change the code line order:
System.out.println("Enter weight in pounds: ");
weight = bodymassScan.nextInt();
System.out.println("Enter height in inches: ");
height = bodymassScan.nextInt();
As the bodymassScan is waiting for your input before printing in System.out.
Console is empty as it is waiting for your input. When you are executing your code its creating an scanner object and when you are using nextint() method its taking the input using scanner object. After that you are printing "Enter weight in pounds" on console.
Case you want it in proper way you need to rearrange the code like:
System.out.println("Enter weight in pounds: ");
weight = bodymassScan.nextInt();
System.out.println("Enter height in inches: ");
height = bodymassScan.nextInt();

When I try to invoke method "calcArea", error message "non-static method calcArea() cannot be referenced from a static context" appears

I've messed around with this for an hour now and can't get it to work. I've also looked this question up but the wording used in answers I've found haven't helped me at all.
Any help would be much appreciated.
Also, the invocation in question is at the very end of the program, inside main.
import java.util.Scanner;
public class Area {
Scanner input = new Scanner (System.in);
/**
* #param args the command line arguments
*/
public static void areaTriangle (double height, double length){
System.out.println((height * length) * .5);
}
public static void areaRectangle (double height, double length,
double width){
System.out.println(height * length * width);
}
public static void areaCircle (double radius){
System.out.println(Math.PI * (radius * radius));
}
public void calcArea (){
double i;
System.out.println("Which shape's area would you like to calculate?: \n"
+ "Enter '1' for Triangle \n"
+ "Enter '2' for Rectangle \n"
+ "Enter '3' for Circle \n"
+ "Enter '0' to quit the program");
i = input.nextDouble();
if (i == 1)
{
System.out.print("Enter the height of your triangle: ");
double height = input.nextDouble();
System.out.print("Enter the height of your length: ");
double length = input.nextDouble();
areaTriangle(height, length);
}
else if ( i == 2)
{
System.out.print("Enter the height of your rectangle: ");
double height = input.nextDouble();
System.out.print("Enter the length of your rectangle: ");
double length = input.nextDouble();
System.out.print("Enter the width of your rectangle: ");
double width = input.nextDouble();
areaRectangle(height, length, width);
}
else if ( i == 3)
{
System.out.print("Enter the radius of your circle");
double radius = input.nextDouble();
areaCircle(radius);
}
else if ( i == 0)
return;
else
System.out.println("Please input a number from 0 - 3");
}
public static void main(String[] args) {
calcArea();
}
}
put static in calcArea
public static void calcArea ()
or you can do this in your main
public static void main(String[] args) {
YourClassName variable= new YourClassName();
variable.calcArea();
}
just change the "YourClassName" to the name of your class and also you can change the variable object

Categories