How to use sub methods properly - java

I want to do an operation for calculating Body Mass Index in my CalBMI method, which depends on the inputs for CalWt and CalHt methods. Then the CalBMI method will return a BMI answer. How can I do such operation?The operation in my CalBMI
import java.util.*;
public class PracticeMethods_returningValues {
static Scanner type=new Scanner(System.in);
public static void main(String[] args)
{
double Wt=0, Ht=0, BMI;
System.out.println("Your Weight in Kg is: " + CalWt(Wt) );
System.out.println("Your Height in meters is: " + CalHt(Ht) );
System.out.println("Your BMI is: " + CalBMI(Wt,Ht) );
}
public static double CalWt(double a){
System.out.println("Please enter your Weight in lbs: ");
double Wt=(type.nextDouble() * .454); //Converts to Kg.
return Wt;
}
public static double CalHt(double b){
System.out.println("\nPlease enter your Height in inches: ");
double Ht=(type.nextDouble() * .025); //Converts to m.
return Ht;
}
public static double CalBMI(double a, double b){
double BMI=a/(Math.pow(b, 2));
return BMI;
}
}

Please tell me if the formula is wrong
public class BMI {
public static double CalWt(Scanner type) {
System.out.println("Please enter your Weight in lbs: ");
return type.nextDouble() * .45359;
}
public static double CalHt(Scanner type) {
System.out.println("Please enter your Height in inches: ");
return type.nextDouble()* .025;
}
public static double CalBMI() {
Scanner type = new Scanner(System.in);
return CalWt(type) / Math.pow(CalHt(type),2);
}
public static void main(String[] args) {
System.out.println(CalBMI());
}
}

Related

Celcius to Fahr using methods but method says undefined

I need help calling my method. It says "the method fahrtoCel" is undefined for the "TempConversion".
import java.util.Scanner;
public class TempConversion {
public static void main(String[] args) {
System.out.println("===CONVERTING TEMPERATURE=====");
ConvertTemp();
}
private static void ConvertTemp(){
Scanner s = new Scanner(System.in);
System.out.println("Press 1: Convert Celcius to Fahrenheit\nPress 2: Convert Fahrenheit to Celcius\n");
int select = s.nextInt();
if (select==1){
System.out.print("Enter the fahrenheit: ");
celtoFahr();
} else if (select==2){
System.out.print("Enter the celcius: ");
fahrtoCel();
} else{
System.out.println("exit");
}
private static void celtoFahr(){
double temperature = s.nextDouble();
double celcius = 5.0/9.0*(temperature-32);
}
private static void fahrtoCel(){
double temperature = s.nextDouble();
double fahrenheit = 9.0/5.0*(temperature+32);
}
}
}
You are missing a closing }
private static void ConvertTemp(){
Scanner s = new Scanner(System.in);
System.out.println("Press 1: Convert Celcius to Fahrenheit\nPress 2: Convert Fahrenheit to Celcius\n");
int select = s.nextInt();
if (select==1){
System.out.print("Enter the fahrenheit: ");
celtoFahr();
} else if (select==2){
System.out.print("Enter the celcius: ");
fahrtoCel();
} else{
System.out.println("exit");
}
// add closing curly
}
private static void celtoFahr(){
...
If you do however, s will be out of scope so change your method to accept the Scanner.
e.g.
private static void ConvertTemp(){
Scanner s = new Scanner(System.in);
....
celtoFahr(s);
....
}
private static void celtoFahr(Scanner s){
....
}
If you use an IDE like Eclipse this error will be immediately obvious

Semicolon expected error in method header

I know that in method headers you aren't supposed to end it with a semicolon; however, all my method headers display the same error: ; expected. This is for the end of the header as well as between two parameters. How would I fix this?
import java.util.Scanner;
import java.text.DecimalFormat;
// This program will calculate the cost of someone's order at a coffee shop with applied possible discounts and tax
public class CoffeeShopWithMethods
{
public static void main (String [] args)
{
double cost = 0;
double discount = 0;
// Scanner allows user to enter values
Scanner user_input = new Scanner(System.in);
String username;
System.out.print("\nEnter your username: ");
username = user_input.next( );
System.out.print ("\nWelcome to Casey's Classic Coffee, " + username + "! \n");
//call methods
displayMenu();
displayOutput(cost, discount, Discounted_cost, tax, Total_cost);
System.out.println("\nThank you " + username + "! Have a nice day!");
}
//outputs the menu to the screen
public static void displayMenu()
{
System.out.println ("\n\tItem\t\tCost\n\t1. Coffee\t$1.50\n\t2. Latte\t$3.50\n\t3. Cappuccino\t$3.25\n\t4. Espresso\t$2.00");
}
//prompts the user to enter item number, returns user input
public static int getItemNumber(int number) //error: ; expected
{
int number;
Scanner number = new Scanner(System.in);
System.out.print ("\nPlease enter the desired item number: ");
number = user_input.nextInt();
return number;
}
//prompts user to enter quantity, returns user input
public static int getQuantity (int quantity) //error: ; expected
{
System.out.print ("\nPlease enter the quantity: ");
quantity = user_input.nextInt();
return quanity;
}
//takes the item number and quantity and returns the subtotal
public static double computeSubTotal (double cost) //error: ; expected
{
int number = getItemNumber(number);
int quantity = getQuantity(quantity);
// Used final double in order to make coffee shop items constant
final double COFFEE = 1.50;
final double LATTE = 3.50;
final double CAPPUCCINO = 3.25;
final double ESPRESSO = 2.00;
double cost = 0;
if (number == 1)
cost = quantity * COFFEE;
else if (number == 2)
cost = quantity * LATTE;
else if (number == 3)
cost = quantity * CAPPUCCINO;
else if (number == 4)
cost = quantity * ESPRESSO;
}
//takes the subtotal and returns true if the user earned a discount; otherwise, returns false
public static boolean discountCheck (double cost) //error: ; expected
{
boolean status;
if (cost >= 10)
{
status = true;
}
else if (cost < 10)
{
status = false;
}
return status;
}
//takes the subtotal and returns the dollar amount of the discount earned by the user
public static double computeDiscount (double cost, double discount) //error: ; expected
{
if (discountCheck() == true)
{
discount = cost * 0.10;
}
else if (discountCheck() != true)
{
discount = 0;
}
return discount;
}
//takes the subtotal and the discount amount and returns the price after the discount is applied
public static double computePriceAfterDiscount (double cost, double discount) //error: ; expected
{
double discount = 0;
double Discounted_cost = 0;
Discounted_cost = cost - discount;
return Discounted_cost;
}
//takes the prices after the discount is applied and tax rate and returns the tax amount
public static double computeTax(double Discounted_cost) //error: ; expected
{
tax = Discounted_cost * 0.07;
return tax;
}
//takes the price after the discount is applied and the tax amount and returns the final total
public static double computeTotal(double Discounted_cost, double tax) //says ; expected
{
Total_cost = Discounted_cost + tax;
return Total_cost;
}
//takes the subtotal, discount amount, price after discount, tax, and final total and displays all the lines of output to the user
public static void displayOutput(double cost, double discount, double Discounted_cost, double tax, double Total_cost) //says ; expected at the end of method header
{
//call methods
double cost = computeSubTotal(cost);
double discount = computeDiscount(cost, discount);
double Discounted_cost = computePriceAfterDiscount(cost, discount);
double tax = computeTax(Discounted_cost);
double Total_cost = computeTotal(Discounted_cost, tax);
System.out.printf ("\nTotal before discount and tax: $%.2f\n ", cost);
System.out.printf("\nCalculated discount: $%.2f\n", discount);
System.out.printf("\nTotal after special discount: $%.2f\n", Discounted_cost);
System.out.printf("\nTax: $%.2f\n", tax);
System.out.printf ("\nTotal cost: $%.2f\n", Total_cost);
}
} //error:reached end of the file while parsing
1)You are using the variables with out declaring:
for eg: compare this snippet with your code snippet.
public static double computeTotal(double Discounted_cost, double tax)
{
double Total_cost = Discounted_cost + tax;
return Total_cost;
}
2)You are invoking undefined methods.
for eg:
you are calling discountCheck() but you have defined like this.
and you have not initialized local variables before using
public static boolean discountCheck (double cost){
boolean status;
if (cost >= 10)
{
status = true;
}
else if (cost < 10)
{
status = false;
}
return status;
}
in the above method status should be initialized.
3) You are declaring duplicate variables that are already available to the methods via parameters.
see the code defined by you here:
public static void displayOutput(double cost, double discount, double Discounted_cost, double tax, double Total_cost)
{
//call methods
double cost = computeSubTotal(cost);
double discount = computeDiscount(cost, discount);
double Discounted_cost = computePriceAfterDiscount(cost, discount);
double tax = computeTax(Discounted_cost);
double Total_cost = computeTotal(Discounted_cost, tax);
System.out.printf ("\nTotal before discount and tax: $%.2f\n ", cost);
System.out.printf("\nCalculated discount: $%.2f\n", discount);
System.out.printf("\nTotal after special discount: $%.2f\n", Discounted_cost);
System.out.printf("\nTax: $%.2f\n", tax);
System.out.printf ("\nTotal cost: $%.2f\n", Total_cost);
}
I would start by extracting your MenuItem(s) into an enum like,
static enum MenuItem {
COFFEE("Coffee", 1.5), LATTE("Latte", 3.5), CAPPUCINO("Cappuccino",
3.25), ESPRESSO("Espresso", 2);
MenuItem(String name, double cost) {
this.name = name;
this.cost = cost;
}
double cost;
String name;
public String toString() {
return String.format("%s $%.2f", name, cost);
}
}
Then your compiler errors were mainly due to declaring duplicate local variable names. I was able to fix the compiler errors and produce something that looks like what you want with,
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter your username: ");
String username = scan.nextLine();
System.out.printf("Welcome to Casey's Classic Coffee, %s!%n", username);
displayMenu();
displayOutput(scan);
System.out.printf("Thank you %s! Have a nice day!", username);
}
// outputs the menu to the screen
public static void displayMenu() {
MenuItem[] items = MenuItem.values();
for (int i = 0; i < items.length; i++) {
System.out.printf("%d %s%n", i + 1, items[i]);
}
}
public static int getItemNumber(Scanner scan) {
System.out.println("Please enter the desired item number: ");
return scan.nextInt();
}
public static int getQuantity(Scanner scan) {
System.out.println("Please enter the quantity: ");
return scan.nextInt();
}
public static double computeSubTotal(Scanner scan) {
int number = getItemNumber(scan);
int quantity = getQuantity(scan);
return quantity * MenuItem.values()[number - 1].cost;
}
public static boolean discountCheck(double cost) {
return (cost >= 10);
}
public static double computeDiscount(double cost) {
if (discountCheck(cost)) {
return cost * 0.10;
}
return 0;
}
public static double computePriceAfterDiscount(double cost, double discount) {
return cost - discount;
}
public static double computeTax(double Discounted_cost) {
return Discounted_cost * 0.07;
}
public static double computeTotal(double Discounted_cost, double tax) {
return Discounted_cost + tax;
}
public static void displayOutput(Scanner scan) {
double cost = computeSubTotal(scan);
double discount = computeDiscount(cost);
double Discounted_cost = computePriceAfterDiscount(cost, discount);
double tax = computeTax(Discounted_cost);
double Total_cost = computeTotal(Discounted_cost, tax);
System.out.printf("Total before discount and tax: $%.2f%n", cost);
System.out.printf("Calculated discount: $%.2f%n", discount);
System.out.printf("Total after special discount: $%.2f%n",
Discounted_cost);
System.out.printf("Tax: $%.2f%n", tax);
System.out.printf("Total cost: $%.2f%n", Total_cost);
}
Here is your entire code corrected and working: http://ideone.com/ta0R21
I really recommend redesigning this. I suggest making use of global variable in some instances.
like the Scanner object. Instead of initializing a new Scanner each method call, use a global
one to handle the entire job

How can i calculate the value(s) of which some are double?

The code I wrote compiles well, but there are certain values that do not calculate. The rate and hours value, tuition and .08 do not calculate. Maybe my code is wrong or something. I am still new to java so i am trying my best. Here is my code:
import java.io.*;
import java.text.DecimalFormat;
import java.util.Scanner;
public class Tuition
{
static double fees;
static double rate;
static double tuition;
private static Scanner sc;
public static void main(String[] args) throws IOException
{
//declare variables
int hours;
//call methods
displayWelcome();
hours = getHours();
rate = getRate(hours);
tuition = calcTuition(hours, rate);
fees = calcFees(tuition);
}
public static void displayWelcome()
{
//welcome statement
System.out.println("Welcome to school that offers distance learning courses");
}
public static int getHours()
{
//declare method variables
int hours = 0;
//a user must enter a string value
System.out.println("Enter total number of hours");
sc = new Scanner(System.in);
try
{
hours = sc.nextInt();
}
catch(NumberFormatException e)
{
System.out.print("Incorrect number");
}
return hours;
}
public static double getRate(int hours)
{
if (hours > 15)
{
System.out.println("rate per credit hour is 44.50");
}
else
{
System.out.println("rate per credit hour is 50.00");
}
return rate;
}
public static double calcTuition(int hours, double rate)
{
tuition =(double)rate * hours;
System.out.print("tuition is" + (tuition));
return tuition;
}
public static double calcFees(double tuition)
{
fees =(double)tuition * .08;
System.out.print("fees are" + (fees));
return fees;
}
public static void displayToatal(double total)
{
DecimalFormat twoDigits = new DecimalFormat("$#,000.00");
System.out.println("the total value is"+ twoDigits.format(tuition + fees));
}
}
In calcTuition()
tuition =(double)rate * hours;
should be
tuition =rate * (double)hours;
: )
You aren't setting the rate. You need a line of code that looks like "rate = x;". You only have println's in the getRate method, but you don't actually set the variable to equal anything.

BMI calculator errors

While doing an assignment for a BMI calculator I keep running into problems with the compiler and the method being used.
The assignment requires me to call a function double bmi to calculate the bmi. I am having problems getting the calling of the function correct. Any help would be great.
One of the errors:
Prog5.java:44: error: illegal start of expression
public static double calculateBmi(double height, double total) {
^
Code:
import java.util.Scanner;
public class Prog5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double avgweight,bmi,total,wReading;
int heightft,heightin,height,k;
String category,weightreading;
System.out.print("Enter the height(in feet and inches separated by spaces): ");
heightft = sc.nextInt();
heightin = sc.nextInt();
height = ((heightft*12)+heightin);
System.out.print("Enter the weight values separated by spaces followed by a negative number: ");
wReading = sc.nextDouble();
While (wReading >=0);
{
total = wReading+total;
Count++;
wReading = sc.nextDouble();
}
avgweight = 0;
total = 0;
weightreading = "Weight readings: " + wReading;
avgweight = total/Count;
public static double calculateBmi(double height, double total) {
{
double bmi = 0;
double total = 0;
double height = 0;
bmi = (height*703) / (total*total);
}
return bmi;
}
if ( bmi > 30)
category=("Obese");
else if (bmi >= 25)
category=("Overweight");
else if (bmi >= 18.5)
category=("Normal");
else {
category=("Underweight");
}
System.out.println("");
System.out.println("Height: "+ heightft + " feet " + heightin + " inches" );
System.out.println("Weight readings: "+ count);
System.out.println("Average weight: " + avgweight + "lbs");
System.out.println("");
System.out.printf("BMI: " + "%.2f", bmi);
System.out.println("");
System.out.println("Category: " + category);
System.out.println("");
}
private static void ElseIf(boolean b) { }
private static void If(boolean b) { }
}
The problem you mention is due to you beginning another method inside main. You instead want a structure something like:
public class Prog5
{
public static void main(String[] args)
{
// code here
}
public static double calculateBMI(double height, double total)
{
//other code
}
}
Your problem is that you are attempting to define a method (namely, public static double calculateBMi) inside a method (public static void main), and Java does not let you do that. (Basically, methods that aren't main need to be attached to a class.)
In the future, you may want to look around before asking this kind of question, since duplicate versions of this have been asked. Your question is basically: Function within a function in Java

Area of Triangle, Java

I'm trying to build an app which computes the area of a triangle, as per my homework assignment. Not quite sure where I'm going wrong, but I input the lengths of the triangle and would like the proper area displayed according to Heron's formula: sqrt (s(s-a) (s-b) (s-c)). All I'm getting for output is -0.0. Here is the code:
import java.lang.Math;
public class Formula
{
double area; double s;
public double findArea(double sideA, double sideB, double sideC)
{
s = 1/2 * (sideA + sideB + sideC);
area = Math.sqrt(s*(s-sideA)*(s-sideB)*(s-sideC));
System.out.println("The area of the triangle is " + area);
return area;
}
}
And then I have another file for the main args
import java.util.Scanner;
public class findTriangleArea {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Formula triangle = new Formula();
double a,b,c;
// input triangle lengths a, b, c
Scanner inputTriangle = new Scanner(System.in);
System.out.println("Please enter triangle side a");
a = inputTriangle.nextDouble();
System.out.println("Please enter triangle side b");
b = inputTriangle.nextDouble();
System.out.println("Please enter triangle side c");
c = inputTriangle.nextDouble();
triangle.findArea(a, b, c);
}
}
1/2 is being computed in integer arithmetic, so like with all integer division, it's truncated -- in this case, to 0. Just write 0.5 and you'll be fine.
public class AreaOfTriangle {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter the height: ");
double height=scanner.nextDouble();
System.out.print("Enter the base: ");
double base=scanner.nextDouble();
scanner.close();
double area=(base*height)/2;
System.out.println("---------------------------");
System.out.println("Area of Triangle is: "+area);
}
}
Heron's Formula:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double a, b, c;
a = sc.nextDouble();
b = sc.nextDouble();
c = sc.nextDouble();
double p = (a + b + c) / 2;
System.out.println(Math.sqrt(p * (p - a) * (p - b) * (p - c)));
}

Categories

Resources