BMI Calculator. Whats wrong? - java

I just want to know how to remove that initialized wgt error. Rest, I want my code to be basic and very simple.
//Program By Aryansh Malviya
//BMI Calculator
import java.util.Scanner;
public class BMICalc
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int cw;
int ch;
int bmi;
int wgt;
int hgt;
int ct;
System.out.print("\nNote: This program is not yet fully functional.\nThere might be issues regarding decimal values. \nProgram has not been equipped to accept or display in decimal values. \nThe program will be updated soon. \nSorry for the inconvinience.");
System.out.print("Enter 1 if you want weight in Kilograms");
System.out.print("Enter 2 if you want weight in Pounds");
cw = input.nextInt();
System.out.print("\nNote: If you choose to enter weight in Pounds, you'd have to enter height in Inches. Else, in meters");
if(cw == 1)
{
System.out.print("\nEnter weight in Kilograms: ");
wgt = input.nextInt();
}
else if(cw == 2)
{
System.out.print("\nEnter weight in Pounds: ");
wgt = input.nextInt();
}
else
{
System.out.print("\nEnter a valid choice and try again!");
}
System.out.print("\nEnter your height: ");
hgt = input.nextInt();
bmi = wgt/(hgt * hgt);
System.out.printf("\nYour weight is: %d", wgt);
System.out.printf("\nYour height is: %d", hgt);
System.out.printf("\n\nYour BMI is: %d", bmi);
System.out.print("\nBMI VALUES");
System.out.print("\nUnderweight: less than 18.5");
System.out.print("\nNormal: between 18.5 and 24.9");
System.out.print("\nOverweight: between 25 and 29.9");
System.out.print("\nObese: 30 or greater");
}
}
When I compile the program I get the error that the variable wgt has not been initialized. Please tell me how to solve this problem.

You have two if statements - but if the user enters neither 1 nor 2 you end up in a part of the code where you try to use wgt without ever initializing it.
You should do two things:
First, initialize wgt when you first declare it (that makes the compiler error go away).
int wgt=0;
would do it.
Next, make sure your program traps the case when cw is neither 1 nor 2. You could use a while loop with a flag, or some other mechanism. Right now, a wrong entry for cw will just keep on going (you print "enter a valid choice" but don't actually go back to the beginning…)
Here is how you fix all that:
import java.util.Scanner;
public class BMICalc
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int cw=0;
int ch;
double bmi;
double wgt=0;
double hgt;
int ct;
double BMIinchPoundFactor = 703;
System.out.print("\nNote: This program is not yet fully functional.\nThere might be issues regarding decimal values. \nProgram has not been equipped to accept or display in decimal values. \nThe program will be updated soon. \nSorry for the inconvinience.");
System.out.print("\nNote: If you choose to enter weight in Pounds, you'd have to enter height in Inches. Else, in meters");
boolean validInput = false;
while (!validInput) {
System.out.print("\nEnter 1 if you want weight in Kilograms");
System.out.print("\nEnter 2 if you want weight in Pounds\n");
cw = input.nextInt();
switch(cw) {
case 1:
System.out.print("\nEnter weight in Kilograms: ");
wgt = input.nextDouble();
validInput=true;
break;
case 2:
System.out.print("\nEnter weight in Pounds: ");
wgt = input.nextDouble();
validInput=true;
break;
default:
System.out.print("\nEnter a valid choice and try again!");
}
}
System.out.print("\nEnter your height: ");
hgt = input.nextDouble();
bmi = wgt/(hgt * hgt);
if(cw==2) bmi *= BMIinchPoundFactor;
System.out.printf("\nYour weight is: %.0f", wgt);
System.out.printf("\nYour height is: %.2f", hgt);
System.out.printf("\n\nYour BMI is: %.1f", bmi);
System.out.print("\nBMI VALUES");
System.out.print("\nUnderweight: less than 18.5");
System.out.print("\nNormal: between 18.5 and 24.9");
System.out.print("\nOverweight: between 25 and 29.9");
System.out.print("\nObese: 30 or greater\n\n");
}
}
I took a few other liberties:
Use double for things that might not be integer values
Clean up the I/O (adding some '\n')
Create a loop that keeps going until you give a valid input
Properly compute BMI wen you give an input in pounds and inches
I'm sure it can be further improved…

There is no guarantee that wgt has been initialized. For example, the user could enter '3' to the first question. You should consider and handle illegal inputs.

bmi = wgt/(hgt * hgt);
You are using wgt here and there is possibilities could not initialize if cw is neither 1 nor 2.

Related

Is there a way to prevent decimal output of a double calculation?

Got this code here and I was wondering if it were possible to make the output that comes from either calculation systems be without a decimal/stop the value at the point before the decimal point. Or even convert a double to an int without any errors.
Please ignore the pointless do while loop at the start, I am aware.
Thank You for any help.
class Main{
public static void main(String[] args)
{
calculation(getSystemChoice());
}
public static int getSystemChoice()
{
Scanner input = new Scanner(System.in); //create scanner
int systemChoice;
do{
System.out.println("If you are using the Metric system, please enter a 1.");
System.out.println("If you are using the Imperial system, please enter a 2.");
System.out.println("To quit the program, please enter a 3.");
systemChoice = input.nextInt();
//Switch start
switch(systemChoice){
case 1:
systemChoice=1;
return systemChoice;
case 2:
systemChoice=2;
return systemChoice;
default: //Currently no working input correction system, likely due to no case for 3. !!!!
System.exit(0);
}
//Switch End
}
while(systemChoice != 1 || systemChoice != 2 || systemChoice != 3);
return systemChoice;
}
//This method takes an int as a parameter(1 or 2) and runs if statements based on the metric or imperial systems.
public static void calculation(int systemChoice)
{
double inches, centimeters, meters, feet;
Scanner input = new Scanner(System.in); //create scanner
//if the user entered one, the result will be in meters and centimeters
if(systemChoice == 1){
System.out.print("Enter amount of meters: ");
meters = input.nextDouble();
System.out.print("Enter amount of centimeters: ");
centimeters = input.nextDouble();
feet = meters * 3.28084;
inches = centimeters / 2.54;
System.out.printf("Feet: %.2f\t " , feet);
System.out.printf("Inches: %.2f\t " , inches);
rerun(systemChoice);
}
// if the user entered 2 then the result will be in feet and inches
else if(systemChoice == 2){
System.out.print("Enter amount of feet: ");
feet = input.nextDouble();
System.out.print("Enter amount of inches: ");
inches = input.nextDouble();
meters = feet / 3.28084;
centimeters = inches * 2.54;
System.out.printf("Meters: %.2f\t " , meters);
System.out.printf("Centimeters: %.2f\t\n " , centimeters);
rerun(systemChoice);
}
}
public static void rerun(int systemChoice)
{
Scanner in = new Scanner(System.in);
System.out.println("\nIf you would like to make another measurement, enter 4.");
System.out.println("Otherwise, you may quit by entering any other number.");
systemChoice = in.nextInt();
if(systemChoice == 4)
{
getSystemChoice();
calculation(systemChoice);
}
else
{
System.exit(0);
}
}
}
You can use casting just before you print it and print it as an integer.
System.out.printf("Inches: %d " , (int)inches)
I do not recommend simply casting to int. Here is an example:
double myValue = 8.65;
System.out.println((int) myValue); // will output 8 as java will always round to the next lower integer
System.out.println(Math.round(myValue)); // will output 9 which obviously is correct (mathematically speaking)
There are a number of potential solutions depending on your exact requirements. Other posters have already mentioned a couple. It's worth bearing in mind the pros and cons of each:
Simply casting to an int or long is the simplest method, but will always round down. It's probably fine for your training example. But in real-world applications, this can cause subtle bugs with values that a double can represent but an int or long can't (e.g. a double can represent the result of 1.0/0 as "infinity", but casting to an int or long will turn this into a large positive integer value-- that can lead to subtle bugs in real-world applications);
You can use Math.round() to use the convention of rounding to up or down to the 'nearest' integer; but this doesn't solve the issue of values that can't be represented;
For other rounding modes, you can use the BigDecimal class: see the BigDecimal.round() method-- many applications won't require this, but some specialist cases might;
To truncate to zero decimal places for output while also dealing with 'special' values, you can use String.format() and specify zero decimal places.
The code for the latter option would look as follows:
double val = ...
System.out.printf("Truncated value is: %.0f", val);
You've probably already seen the 'simple casting' option, but it would look like this:
double val = ...
long truncatedVal = (long) val;
System.out.println("Truncated value = " + truncatedVal);

how to store a calculation from an input to memory, input repeats, first calculation from input is added to second calculation from input and so on?

I need some help with a program I'm trying to make using Java.
I'm currently a freshman in Information Technology and for finals, we have to do an electrical billing program of some sort I've already done some code but it won't work the way I want it to. Can anyone help me fix it?
flow of program:
1)user inputs multiple numbers to be calculated
2)program calculates it
3)the result of the calculation from step 2 is stored somewhere
4)program asks user if they want to input again
5)if user chooses input again the process repeats from step 1 to 2 and is added to the first calculation and so on and so forth
static Scanner console = new Scanner (System.in);
Double loopFor=0.0;
Double w,h,kwh,t;
System.out.print("\nHello and welcome to Pikabill. The electricity bill estimate calculator.");
while(true) {
do {
System.out.print("\nEnter what is being asked. You might have to refer to labels on your appliances");
System.out.print("\nWATTAGE (W): ");
w=console.nextDouble();
System.out.print("\nUSAGE (in HOURS): ");
h=console.nextDouble();
System.out.print("\nELECTRICITY RATE (kWh): ");
kwh=console.nextDouble();
t=(w*h)/1000*kwh;
System.out.print("\nCOST: " + t);
loopFor += t;
System.out.print("\nWould you like to continue? YES [y] No [n]");
String c= console.nextLine();
if(c.equalsIgnoreCase("n")){
break;
}
}
while (loopFor !=0);
}
}
}
somehow, when I run this the calculation works fine, but when it comes to displaying the t (the calculation), it shows the "do you want to continue" just fine but the "Hello and welcome to Pikabill...." shows on the next line even though i havent pressed y. It also doesn't add the previous calculations to the newer ones as well.
This piece of code will work.
import java.util.Scanner;
public class ElectricalBillingProgram
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
Double loopFor = 0.0;
Double w, h, kwh, t;
for (int i = 0;; i++)
{
System.out.print("\nEnter what is being asked. You might have to refer to labels on your appliances");
System.out.print("\nWATTAGE (W): ");
w = console.nextDouble();
System.out.print("\nUSAGE (in HOURS): ");
h = console.nextDouble();
System.out.print("\nELECTRICITY RATE (kWh): ");
kwh = console.nextDouble();
t = (w * h) / 1000 * kwh;
System.out.print("\nCOST: " + t);
loopFor += t;
System.out.print("\nWould you like to continue? YES [y] No [n]");
String c = console.next();
if (c.equalsIgnoreCase("n"))
{
break;
}
}
}
}
Observations from your code:
Never mixup "while" and "doWhile", if it confuses you, use "for" loop.
use console.next() instead of console.nextLine().
Happy learning!
This should be your code -
Scanner console = new Scanner(System.in);
Double loopFor = 0.0;
Double w, h, kwh, t;
System.out.println("Hello and welcome to Pikabill. The electricity bill estimate calculator.");
while (true) {
System.out.println("Enter what is being asked. You might have to refer to labels on your appliances");
System.out.println("WATTAGE (W): ");
w = console.nextDouble();
System.out.println("USAGE (in HOURS): ");
h = console.nextDouble();
System.out.println("ELECTRICITY RATE (kWh): ");
kwh = console.nextDouble();
t = (w * h) / 1000 * kwh;
loopFor += t;
System.out.println("COST:\t" + t);
System.out.println("loopFor:\t" + loopFor);
System.out.println("Would you like to continue? YES [y] No [n]");
String c = console.next();
if (c.equals("n")) {
break;
}
}

quit java program when an alphabetic character is entered

i have to make a body mass index calculator in java for an assignment, and if the user enters an alphabetic character when it asks for weight, i want the program to quit and display a message. i need help creating the if statement. here is what i have (which isn't working). i have tried various other inequality symbols with no success. i thought i may have to use a if (between command) but i did not discover a way to make that work with the weight variable.
The error i recieve is as follows
Lab4.java:21: error cannot find symbol
if (weight <= Z)
^
public class Lab4
{
public static void main (String[] args)
{
Scanner kb = new Scanner (System.in);
System.out.println("enter e for english or m for metric");
String choice;
choice = kb.nextLine();
char firstchar;
firstchar = choice.charAt(0);
boolean english;
english = firstchar == 'e';
if (english)
{
// prompt the user to input their weight in pounds
System.out.println("Enter your weight in pounds");
double weight = kb.nextDouble();
if (weight <= Z)
{
System.out.println("letters are not an acceptable weight");
System.exit(0);
}
// prompt the user to input their height in inches
System.out.println("Enter your height in inches");
double height = kb.nextDouble();
if (height == 0.0)
{
System.out.println("0 is not a valid height");
System.exit(0);
}
// make bmi to an integer and compute bmi by dividing weight by height^2 * 750
int bmi = (int)(weight/(height*height)*703);
// have the computer display height, wieght, and bmi
System.out.printf("your weight is %8.2f", weight);
System.out.println(" pounds");
System.out.printf("your height is %8.2f", height);
System.out.println(" inches");
System.out.println("your BMI is " + bmi);
if (bmi <= 24)
System.out.println("Normal Bodyweight");
else
{
if (bmi > 30)
System.out.println("Obese");
else
System.out.println("Overweight");
If weight is the input string. You can use the isAlpha function from: https://stackoverflow.com/a/5238524/1926621
Then do if (isAlpha(weight) ) as the condition for checking if the input is alphabetical or not.
In your code, you are reading weight as double using kb.nextDouble() which will throw InputMismatchException and the program will be terminated even before performing/entering your if check (i.e., weight <= Z).
Also, one more important point is that you can't compare double with char type directly i.e., like weight <= Z
So, read weight as string using scanner.nextLine() as shown below and then check if it does not contain alphabets (using regex) as shown below:
String weight = kb.nextLine();
if(!weight.contains(/^\d*\.?\d*$/)) {
System.out.println("letters are not an acceptable weight");
System.exit(0);
}
Considering weight is string -
if(!weight.matches("[-+]?\\d*\\.?\\d+")){
System.out.println("Ikke akseptert. Quitter");
System.exit(0);
}

Java Tip Calculator for newbie

I hope I'm posting in the right place.
I'm pretty new to Java (meaning this is only my third program besides 'hello world').
I have a tip calculator I'm working on for an assignment. I'm not getting an 'error' as such,
but the method for splitting the bill always seems to think each customer pays 'infinity'.
I have my program set up in two classes: tipCalc1 and tipCalc2 (no points for originality of course).
The program appears to run without issue besides the 'infinity' issue.
Here's what I have so far. Any assistance appreciated, thanks.
***TipCalc1 Class:***
import java.util.Scanner;
public class Tipcalc1
{
public static void main(String[] args)
{
System.out.println("Welcome to Tip Calculator! ");
TipCalc2 Calculator = new TipCalc2();
System.out.println("Please enter the bill amount: ");
TipCalc2.calBill();
System.out.println("What percentage would you like to tip?: ");
Calculator.percTip();
}
}
***And the tipCalc2 class which does the dirty work:***
import java.util.Scanner;
public class TipCalc2
{
static double bill;
double tip;
double total;
double split;
double splitPrompt;
double Y;
double N;
double billPerPerson;
static Scanner scan = new Scanner(System.in);
public static void calBill()
{
bill = scan.nextDouble();
}
public void percTip()
{
tip = scan.nextDouble();
if(tip<1)
{
total = bill * tip;
}
else total = bill * (tip/100);
System.out.println("Your total is: " + total);
Split();
}
public void Split()
{
System.out.println("Would you like to split the bill? ");
System.out.println("Enter 1 for YES or 0 for NO: ");
splitPrompt = scan.nextDouble();
if(splitPrompt == 0)
{
System.out.println("Your total is: " + total);
System.out.println("Thankyou. Goodbye.");
System.out.println("End Program");
}
if(splitPrompt == 1)
{
System.out.println("How many ways would you like to split the bill? ");
splitPrompt = scan.nextDouble();
billPerPerson = total / split;
System.out.println("Each person pays: " + billPerPerson);
System.out.println("Thankyou. Goodbye.");
System.out.println("End Program.");
}
else System.out.println("Invalid Entry");
}
}
The default value for split (because you have not initialized it with another value) is 0.0, therefore, when you do
billPerPerson = total / split;
you divide by 0.0, so you will get Infinity.
Notes:
Since your variable splitPrompt is double and computers doesn't store real values with a 100% accuracy, you shouldn't compare it with 0.0. Since this variable will store 0 or 1 for input, you can declare it as int, which will be accurate.
Try to follow Java naming conventions. Use mixedCase for methods/variables and use CamelCase for classes/interfaces.
In the method split(), you should use an if-else if-else structure:
if(splitPrompt == 0) {
...
}
else if(splitPrompt == 1) {
...
}
else {
...
}
Silly mistake.
Change
System.out.println("How many ways would you like to split the bill?
splitPrompt = scan.nextDouble();
to
System.out.println("How many ways would you like to split the bill?
split = scan.nextDouble();
since you never change split which, like all double variables, is initialized to 0.0.
Also, you should use ints where appropriate as not all of the numbers should be doubles. Or even better, use 'y' and 'n' chars.
Class TipCalc2
//Total = **bill** * (gets percentage in decimal 15 = 0.15) + **bill**
Line 18 needs to be:
total = bill * (tip / 100) + bill;
Line 36/37 needs to be:
split = splitPrompt = scan.nextInt();
billPerPerson = total / split;
//You're dividing billPerPerson = total by ZERO (split);
Line 36/37 original:
billPerPerson = total / split;

monthly payment calculator

I have some code which I find to keep giving me a dividing by 0 error.
It is suppose to calculate the monthly payment amount!
import java.io.*;
public class Bert
{
public static void main(String[] args)throws IOException
{
//Declaring Variables
int price, downpayment, tradeIn, months,loanAmt, interest;
double annualInterest, payment;
String custName, inputPrice,inputDownPayment,inputTradeIn,inputMonths, inputAnnualInterest;
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
//Get Input from User
System.out.println("What is your name? ");
custName = dataIn.readLine();
System.out.print("What is the price of the car? ");
inputPrice = dataIn.readLine();
System.out.print("What is the downpayment? ");
inputDownPayment = dataIn.readLine();
System.out.print("What is the trade-in value? ");
inputTradeIn = dataIn.readLine();
System.out.print("For how many months is the loan? ");
inputMonths = dataIn.readLine();
System.out.print("What is the decimal interest rate? ");
inputAnnualInterest = dataIn.readLine();
//Conversions
price = Integer.parseInt(inputPrice);
downpayment = Integer.parseInt(inputDownPayment);
tradeIn = Integer.parseInt(inputTradeIn);
months = Integer.parseInt(inputMonths);
annualInterest = Double.parseDouble(inputAnnualInterest);
interest =(int)annualInterest/12;
loanAmt = price-downpayment-tradeIn;
//payment = loanAmt*interest/a-(1+interest)
payment=(loanAmt/((1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
//Output
System.out.print("The monthly payment for " + custName + " is $");
System.out.println(payment);
// figures out monthly payment amount!!!
}
}
the problem occurs when attempting to set the payment variable.
i don't understand why it keeps coming up with dividing by 0 error.
You have declared your variables as Int so 1/interest and 1/(interest*Math.pow(1+interest,-months)) will return 0. Change the type of your variables to float or double.
One suggestion to you, is that you should learn to "backwards slice" your code.
This means that when you see that you're getting a DivideByZeroException you should look at your code, and say, "why could this happen?"
In your case, let's look at this:
payment=(loanAmt/((1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
So, now, Math.pow will never return anything zero (as it's a power), so it must be the case that interestis zero. Let's find out why:
interest =(int)annualInterest/12;
So now, integer division in Java truncates. This means that if you have .5 it will be cut off, and turned into zero. (Similarly, 1.3 will be truncated to 0).
So now:
annualInterest = Double.parseDouble(inputAnnualInterest);
This implies that you are passing in something that gets parsed to a value that is less than 12. If it were greater than 12 then you would get something else.
However, you might just be passing in an invalid string, for example, passing in "hello2.0" won't work!
This will be rounding always to 0. So it is trowing exception.
(1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
Use float type instead of int. Learn how they works.
package computeloan;
import java.util.Scanner;
public class ComputeLoan {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" Enter Yearly Interest Rate : ");
double annualIntersetRate = input.nextDouble();
double monthlyIntersetRate = annualIntersetRate / 1200;
System.out.print(" Enter Number of years : ");
int numberOfYears = input.nextInt();
// Enter loan amount
System.out.print(" Enter Loan Amount : ");
double loanAmount = input.nextDouble();
double monthlyPayment = loanAmount * monthlyIntersetRate /(1-1/Math.pow(1+monthlyIntersetRate,numberOfYears*12 ));
double totalPayment = monthlyPayment * numberOfYears * 12;
//Calculate monthlyPaymeent and totalPayment
System.out.println(" The Monthly Payment Is : " +(int)(monthlyPayment*100) /100.0);
System.out.println(" The Total Payment Is : " +(int)(totalPayment*100) /100.0 );
}
}

Categories

Resources