getting NaN on my java project - java

I just started learning java 2 months ago and i have a project to create an BMI calculator which can use the imperial system and metric system .
I created it but I get Nan as answer for BMI. I don't have any syntax errors in it and I don't understand why I am getting NaN`
import java.util.Scanner;
import java.util.InputMismatchException;
public class BmiCalculator
{
Scanner input = new Scanner(System.in);
// ConvertSystem convert = new ConvertSystem();
String name;
double height;
double stone;
double pound;
double feet;
double inch;
double kg;
double meters;
double wheight;
double BMI;
int MetricOrImperial ;
public void getIntro()
{
System.out.println("Welcome to the Body Mass Index Calculator");
System.out.println("Please enter your name:");
name = input.nextLine();
System.out.printf("Hello %s !\n", name);
}
public void metricOrImperial()
{ boolean continueLoop = true;
do
{
try
{
System.out.println("Please choose which measurement system you want to use; \n ");
System.out.println("For Imperial type number 1:\nFor Metric type number 2 \n");
MetricOrImperial = input.nextInt();
continueLoop = false;
}// end try
catch ( InputMismatchException inputMismatchException )
{
System.err.printf( "\nException: %s\n",inputMismatchException );
input.nextLine();
System.out.println
("\nYou must enter number 1 or 2\n Please try again" );
}// end catch
}// end do
while (continueLoop);
} // end imperialOrMetric
public void getImperial()
{ boolean continueLoop = true;
do{
try{
if (MetricOrImperial == 1)
{
System.out.println("Please enter your wheight in Stones: ");
stone = input.nextDouble();
System.out.println("Enter your wheight in Pounds: ");
pound = input.nextDouble();
System.out.println("Please enter your height in feets: ");
feet = input.nextDouble();
System.out.println("Enter your height in inch: ");
inch = input.nextDouble();
}
continueLoop= false;
} // end try
catch ( InputMismatchException inputMismatchException )
{
System.err.printf( "\nException: %s\n",inputMismatchException );
input.nextLine();
System.out.println
("\nPlease enter only number\n Try again!" );
}// end catch
}while(continueLoop);
}
public void getMetric()
{ boolean continueLoop = true;
do{
try{
if (MetricOrImperial == 2)
{
System.out.println("Please enter your wheight in Kg ");
kg = input.nextDouble();
System.out.println("Please enter your height in Meters: ");
meters = input.nextDouble();
}
continueLoop= false;
} // end try
catch ( InputMismatchException inputMismatchException )
{
System.err.printf( "\nException: %s\n",inputMismatchException );
input.nextLine();
System.out.println
("\nPlease enter only number\n Try again!" );
}// end catch
}while(continueLoop);
}// end getMetric
public void convertToMetric()
{
if (MetricOrImperial == 1)
{
wheight = (stone * 6.3502) + (pound * 0.4536);
height = (feet * 0.3048) + (inch * 0.0254);
}
else
{
wheight = kg;
height = meters;
}
}
public void getBmi()
{
BMI = wheight / (height* height) ;
System.out.println(BMI);
}
} // endBMI calculator
`
import java.util.*;
public class BmiCalculatorTest extends BmiCalculator {
public static void main(String[] args)
{
BmiCalculator bmi = new BmiCalculator();
bmi.getIntro();
bmi.metricOrImperial();
bmi.getImperial();
bmi.getMetric();
bmi.getBmi();

The reason it is not working is that you never called on bmi.convertToMetric() to calculate height.
If you run this code your code works
public static void main(String[] args)
{
BmiCalculator bmi = new BmiCalculator();
bmi.getIntro();
bmi.metricOrImperial();
bmi.getImperial();
bmi.getMetric();
bmi.convertToMetric(); //Added call to converToMetric to calculate height
bmi.getBmi();
}
The reason you got NaN is that height was set to 0.0 so you tried dividing 0.0/0.0 in getBmi()

Related

Using Loops to Reset Basic Financial Calculator

I cannot quite figure out how to make my basic financial calculator be able to run a new set of numbers without closing the program. What I currently have allows me to run one set of numbers, and when I get to "Would you like to continue?", when I press 1 it simply will print "Would you like to continue?" however many times I press 1. Here is what I have so far:
package Register;
import java.util.Scanner;
public class Register {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Register myRegister = new Register();
System.out.println("Welcome to the Electricity Bill calculator.");
System.out.print("Enter amount of electricity (kW) used in the daytime: ");
float num1 = scan.nextFloat();
System.out.print("Enter amount of electricity (kW) used in the evening: ");
float num2 = scan.nextFloat();
System.out.print("Enter rate for daytime: ");
float num3 = scan.nextFloat();
System.out.print("Enter rate for evening: ");
float num4 = scan.nextFloat();
float day1 = num1 * num3;
float night2 = num2 * num4;
float total = day1 + night2;
{
System.out.println("Electricity Bill: $" + total);
}
System.out.println("");
boolean keepLooping = true;
while (keepLooping) {
System.out.print("Would you like to continue? Press 1 continue or 0 to exit.");
int answer = scan.nextInt();
if(answer == 0) {
keepLooping = false;
} else {
keepLooping = true;
}
}
}
}
You have used while loop around asking choice statements only. So use while loop at the beginning in main method as below:
import java.util.Scanner;
public class Register{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Register myRegister = new Register();
boolean keepLooping = true;
while(keepLooping) {
System.out.println("Welcome to the Electricity Bill calculator.");
System.out.print("Enter amount of electricity (kW) used in the daytime: ");
float num1 = scan.nextFloat();
System.out.print("Enter amount of electricity (kW) used in the evening: ");
float num2 = scan.nextFloat();
System.out.print("Enter rate for daytime: ");
float num3 = scan.nextFloat();
System.out.print("Enter rate for evening: ");
float num4 = scan.nextFloat();
float day1 = num1 * num3;
float night2 = num2 * num4;
float total = day1 + night2;
System.out.println("Electricity Bill: $" + total);
System.out.println("");
System.out.print("Would you like to continue? Press 1 continue or 0 to exit.");
int answer = scan.nextInt();
if(answer == 0) {
keepLooping = false;
} else {
keepLooping = true;
}
}
}
}

How do I validate user input in Java

I wrote a bmi calculator program and I want to validate user input so that the user would not enter a negative number for the height or weight input.
How do I do this? I am new to Java, so I have no idea.
import java.util.Scanner;
public class BMICalculator {
public static void main(String[] args) throws Exception {
calculateBMI();
}
private static void calculateBMI() throws Exception {
System.out.print("Please enter your weight in kg: ");
Scanner s = new Scanner(System.in);
float weight = s.nextFloat();
System.out.print("Please enter your height in cm: ");
float height = s.nextFloat();
float bmi = (100*100*weight)/(height*height);
System.out.println("Your BMI is: "+bmi);
printBMICategory(bmi);
s.close();
}
private static void printBMICategory(float bmi) {
if(bmi < 24) {
System.out.println("You are underweight");
}else if (bmi < 29) {
System.out.println("You are healthy");
}else if (bmi < 34) {
System.out.println("You are overweight");
}else {
System.out.println("You are OBESE");
}
}
}
you can keep asking for value until the user input a valid number
private float readZeroOrPositiveFloat(Scanner scanner , String promptMessage)
{
float value = -1;
while(value < 0){
System.out.println(promptMessage);
value = scanner.nextFloat();
}
return value;
}
private static void calculateBMI() throws Exception {
System.out.print("Please enter your weight in kg: ");
Scanner s = new Scanner(System.in);
float weight = readZeroOrPositiveFloat(s , "Please enter your weight in kg: ");
float height = readZeroOrPositiveFloat(s , "Please enter your height in cm: ");
float bmi = (100*100*weight)/(height*height);
System.out.println("Your BMI is: "+bmi);
printBMICategory(bmi);
s.close();
}
Just to handle negative inputs and keep asking for valid input,
boolean flag = true;
while(flag){
System.out.print("Please enter your weight in kg: ");
int weight = sc.nextInt();
System.out.print("Please enter your height in cm: ");
int height = sc.nextInt();
if(weight >= 0 && height >= 0){
float bmi = (100*100*weight)/(height*height);
flag = false;
}else{
System.out.println("Invalid Input");
}
}
To handle all the unexpected inputs and keep asking for valid input,
boolean flag = true;
while(flag){
Scanner sc = new Scanner(System.in);
try{
System.out.print("Please enter your weight in kg: ");
int weight = sc.nextInt();
System.out.print("Please enter your height in cm: ");
int height = sc.nextInt();
if(weight >= 0 && height >= 0){
float bmi = (100*100*weight)/(height*height);
flag = false;
}else{
System.out.println("Invalid Input");
}
}catch(Exception e){
System.out.println("Invalid Input");
}
}
When you get input from the scanner, you could use an if statement to make sure the value is not negative. For example:
if(input value <= 0){
System.out.println("Invalid Input");
}else { *program continues* }

How to pass parameters values from one method to another one in the same class

I'm writing this code for an ATM simulator, with deposit, withdrawal and balance inquiry functionality. The code needs to be written with methods and not switch statements.
My deposit method works, but I have issues with both the withdraw and balanceInquiry methods. I would like to have checkAc_bal accessible to all methods, in order to perform calculations. I'm new on Java, and I'm trying to wrap my head on methods behaviors. Thanks so much.
...
import java.util.Scanner;
public class Main
{
public static void showMenu()
{
Scanner sc = new Scanner(System.in) ;
String input = null ;
do
{
input = showOptions(sc) ;
if(input != null)
{
switch(input.trim())
{
case "1" : deposit(sc) ;
break ;
case "2" : withdraw(sc);
break ;
case "3" : balanceInquiry() ;
break ;enter code here
case "4" : System.exit(0);
default : System.out.println("Wrong option entered. Exiting application") ;
System.exit(0);
}
}
}while(true) ;
}
public static String showOptions(Scanner sc)
{
System.out.println("********************Welcome to ATM Machine******************** ");
System.out.println("Enter Option");
System.out.println("1. Deposit");
System.out.println("2. Withdrawal");
System.out.println("3. Balance Inquiry");
System.out.println("4. Exit\n");
String input = sc.nextLine() ;
return input ;
}
public static void deposit (Scanner sc) {
int checkAc_bal = 0;
System.out.print("Enter amount to be deposited:");
int deposit;
Scanner s = new Scanner(System.in);
deposit = s.nextInt();
//int checkAc_bal = 0;
checkAc_bal = checkAc_bal + deposit;
System.out.println("Your Money has been successfully deposited");
System.out.println("Balance: " +checkAc_bal);
}
public static void withdraw (Scanner sc){
System.out.print("Enter money to be withdrawn:");
int withdraw;
Scanner s = new Scanner(System.in);
withdraw = s.nextInt();
if(withdraw<=checkAc_bal)
{
checkAc_bal = checkAc_bal - withdraw;
System.out.println("Please collect your money");
}
else
{
System.out.println("Insufficient Balance");
}
System.out.println("");
}
public static void balanceInquiry () {
System.out.println("Balance: " + checkAc_bal);
}
public static void main(String[] args) {
showMenu();
}
}
If you want your int to be accessible to other methods, you need to declare it in the scope of the whole class and not inside a method. Try declaring checkAc_bal in the Main class.
define it as a class member:
import java.util.Scanner;
public class Main
{
static int checkAc_bal = 0; //<------------------------add this
public static void showMenu()
{
Scanner sc = new Scanner(System.in) ;
String input = null ;
do
{
input = showOptions(sc) ;
if(input != null)
{
switch(input.trim())
{
case "1" : deposit(sc) ;
break ;
case "2" : withdraw(sc);
break ;
case "3" : balanceInquiry() ;
break ;enter code here
case "4" : System.exit(0);
default : System.out.println("Wrong option entered. Exiting application") ;
System.exit(0);
}
}
}while(true) ;
}
public static String showOptions(Scanner sc)
{
System.out.println("********************Welcome to ATM Machine******************** ");
System.out.println("Enter Option");
System.out.println("1. Deposit");
System.out.println("2. Withdrawal");
System.out.println("3. Balance Inquiry");
System.out.println("4. Exit\n");
String input = sc.nextLine() ;
return input ;
}
public static void deposit (Scanner sc) {
// int checkAc_bal = 0; <---------------- remove this
System.out.print("Enter amount to be deposited:");
int deposit;
Scanner s = new Scanner(System.in);
deposit = s.nextInt();
//int checkAc_bal = 0;
checkAc_bal = checkAc_bal + deposit;
System.out.println("Your Money has been successfully deposited");
System.out.println("Balance: " +checkAc_bal);
}
public static void withdraw (Scanner sc){
System.out.print("Enter money to be withdrawn:");
int withdraw;
Scanner s = new Scanner(System.in);
withdraw = s.nextInt();
if(withdraw<=checkAc_bal)
{
checkAc_bal = checkAc_bal - withdraw;
System.out.println("Please collect your money");
}
else
{
System.out.println("Insufficient Balance");
}
System.out.println("");
}
public static void balanceInquiry () {
System.out.println("Balance: " + checkAc_bal);
}
public static void main(String[] args) {
showMenu();
}
}
You have three queries, here are the answers :
Declare the variable globally to be accessible from all the methods.
Not to use switch case (U need to use if-else in that case)
How to pass parameters to methods in same class ?
I see you already did this in your code. You called other methods by parameters and received them as well.
Or frame your question well , as what exactly you need.
So here is the complete code :
import java.util.Scanner;
public class Main{
static int checkAc_bal = 0; // <---- declare on class scope
public static void showMenu() {
Scanner sc = new Scanner(System.in) ;
String input = null ;
do {
input = showOptions(sc) ;
if(input != null) {
// removed the switch-case and if-else used
if(input.trim().equals("1")) {deposit();}
else if(input.trim().equals("2")) {withdraw();}
else if(input.trim().equals("3")) {balanceInquiry();}
else if(input.trim().equals("4")) {System.exit(0);}
else {
System.out.println("Wrong option entered. Exiting application") ;
System.exit(0);
}
}
}while(true) ;
}
public static String showOptions(Scanner sc){
System.out.println("********************Welcome to ATM Machine******************** ");
System.out.println("Enter Option");
System.out.println("1. Deposit");
System.out.println("2. Withdrawal");
System.out.println("3. Balance Inquiry");
System.out.println("4. Exit\n");
String input = sc.nextLine() ;
return input ;
}
public static void deposit () {
System.out.print("Enter amount to be deposited:");
int deposit;
Scanner s = new Scanner(System.in);
deposit = s.nextInt();
checkAc_bal = checkAc_bal + deposit;
System.out.println("Your Money has been successfully deposited");
System.out.println("Balance: " +checkAc_bal);
}
public static void withdraw (){
System.out.print("Enter money to be withdrawn:");
int withdraw;
Scanner s = new Scanner(System.in);
withdraw = s.nextInt();
if(withdraw<=checkAc_bal) {
checkAc_bal = checkAc_bal - withdraw;
System.out.println("Please collect your money");
} else {
System.out.println("Insufficient Balance");
}
System.out.println("");
}
public static void balanceInquiry () {
System.out.println("Balance: " + checkAc_bal);
}
public static void main(String[] args) {
showMenu();
}
}
Output :
********************Welcome to ATM Machine********************
Enter Option
1. Deposit
2. Withdrawal
3. Balance Inquiry
4. Exit
1
Input : 1
Enter amount to be deposited:100
Your Money has been successfully deposited
Balance: 100
********************Welcome to ATM Machine********************
Enter Option
1. Deposit
2. Withdrawal
3. Balance Inquiry
4. Exit
1
Input : 1
Enter amount to be deposited:200
Your Money has been successfully deposited
Balance: 300
********************Welcome to ATM Machine********************
Enter Option
1. Deposit
2. Withdrawal
3. Balance Inquiry
4. Exit
1
Input : 1
Enter amount to be deposited:200
Your Money has been successfully deposited
Balance: 500
********************Welcome to ATM Machine********************
Enter Option
1. Deposit
2. Withdrawal
3. Balance Inquiry
4. Exit
3
Input : 3
Balance: 500
********************Welcome to ATM Machine********************
Enter Option
1. Deposit
2. Withdrawal
3. Balance Inquiry
4. Exit

Exception Handling for no user input in Java

I am trying to get my program to exception handle for if the user inputs nothing so they will get an error message of "Error, enter a dollar amount greater than 0" or "Error, Enter a 1, 2 or 3". As of now, the program does nothing if the user just hits "enter" with no input....
import java.util.Scanner;
import java.util.*;
import java.text.DecimalFormat;
public class Candleline
{
public static void main(String[] args)
{
//initiate scanner
Scanner input = new Scanner(System.in);
System.out.println("\tCandleLine - Candles Online");
System.out.println(" ");
//declare variables and call methods
double candleCost = getCandleCost();
int shippingType = getShippingType();
double shippingCost = getShippingCost(candleCost, shippingType);
output(candleCost, shippingCost);
}
public static double getCandleCost()
{
//get candle cost and error check
Scanner input = new Scanner(System.in);
boolean done = false;
String inputCost;
double candleCost = 0;
while(!done)
{
System.out.print("Enter the cost of the candle order: ");
try
{
inputCost = input.next();
candleCost = Double.parseDouble(inputCost);
if (inputCost == null) throw new InputMismatchException();
if (candleCost <=0) throw new NumberFormatException();
done = true;
}
catch(InputMismatchException e)
{
System.out.println("Error, enter a dollar amount greater than 0");
input.nextLine();
}
catch(NumberFormatException nfe)
{
System.out.println("Error, enter a dollar amount greater than 0");
input.nextLine();
}
}
return candleCost;
}
public static int getShippingType()
{
//get shipping type and error check
Scanner input = new Scanner(System.in);
boolean done = false;
String inputCost;
int shippingCost = 0;
while(!done)
{
System.out.println(" ");
System.out.print("Enter the type of shipping: \n\t1) Priority(Overnight) \n\t2) Express (2 business days) \n\t3) Standard (3 to 7 business days) \nEnter type number: ");
try
{
inputCost = input.next();
shippingCost = Integer.parseInt(inputCost);
if (inputCost == null) throw new InputMismatchException();
if (shippingCost <=0 || shippingCost >= 4) throw new NumberFormatException();
done = true;
}
catch(InputMismatchException e)
{
System.out.println("Error, enter a 1, 2 or 3");
input.nextLine();
}
catch(NumberFormatException nfe)
{
System.out.println(" ");
System.out.println("Error, enter a 1, 2 or 3");
input.nextLine();
}
}
return shippingCost;
}
public static double getShippingCost(double candleCost, int shippingType)
{
//calculate shipping costs
double shippingCost = 0;
if (shippingType == 1)
{
shippingCost = 16.95;
}
if (shippingType == 2)
{
shippingCost = 13.95;
}
if (shippingType == 3)
{
shippingCost = 7.95;
}
if (candleCost >= 100 && shippingType == 3)
{
shippingCost = 0;
}
return shippingCost;
}
public static void output(double fCandleCost, double fShippingCost)
{
//display the candle cost, shipping cost, and total
Scanner input = new Scanner(System.in);
DecimalFormat currency = new DecimalFormat("$#,###.00");
System.out.println("");
System.out.println("The candle cost of " + currency.format(fCandleCost) + " plus the shipping cost of " + currency.format(fShippingCost) + " equals " + currency.format(fCandleCost+fShippingCost));
}
}
Replace input.next();
with input.nextLine();
You can write a method that validates the input before proceeding. It can keep asking for inputs if user enters something that is not valid. E.g. below example demonstrates how to validate an integer input:
private static int getInput(){
System.out.print("Enter amount :");
Scanner scanner = new Scanner(System.in);
int amount;
while(true){
if(scanner.hasNextInt()){
amount = scanner.nextInt();
break;
}else{
System.out.println("Invalid amount, enter again.");
scanner.next();
}
}
scanner.close();
return amount;
}

Exiting a program with System.exit(0) in java

I am a little confused about how to implement System.exit(0); in my program. What I want to have happen is for the user to type the word "exit" and for the program to terminate. I would also like the program to return "0.0" when "clear" is entered, but I think I am having trouble working with my variables because num1 and num2 are doubles but I want "exit" and "clear" to be acceptable inputs, as well.
If anyone has any insight, that would be greatly appreciated. Here is my code:
package projectapcs;
/**
*
* #author Apple
*/
import java.util.Scanner;
public class ProjectAPCS {
public static void exit(int x){
}
public static void clear(int y){
}
public static void main(String[] args) {
double num1;
double num2;
char char1;
String operation;
Scanner input = new Scanner(System.in);
System.out.println
("Enter 'exit' to quit the calculator, 'help' for more options or 'continue' to use the calculator");
System.out.println
("\nEnter the first number:");
num1 = input.nextInt();
System.out.println
("Display:" + num1);
System.out.println("Please enter operation:");
operation = input.next();
System.out.println("Enter the second number:");
num2 = input.nextInt();
System.out.println ("Display:" + num2);
if ("+".equals(operation)){
System.out.println((num1 + num2));
}
else if ("-".equals(operation)){
System.out.println((num1 - num2));
}
else if ("/".equals(operation)){
System.out.println((num1 / num2));
}
else if ("*".equals(operation)){
System.out.println((num1 * num2));
}
else if ("-x".equals(operation)){
System.out.println (-num1);
}
else if ("x^2".equals(operation)){
System.out.println (num1 * num1);
}
else if ("sqrt".equals(operation)){
System.out.println (Math.sqrt(num1));
}
else if ("H".equals(num1)){
System.out.println("Type + for the addition of values");
System.out.println("Type - for the substraction of values");
System.out.println("Type * for the multiplcation of values");
System.out.println("Type / for the division of values");
System.out.println("Type negate for the negation of values");
System.out.println("Type ^2 for squaring of values");
}
else if("E".equals(num1)){
System.out.println ("Calculator program terminated...");
System.exit(0);
}
}
}
If you want to allow arbitrary inputs, read input as a String, then convert to double as needed:
String input = scanner.next();
if (input.equals("exit")) {
exit();
else if (input.equals("clear")) {
clear();
} else {
try {
double number = Double.parseDouble(input);
/* do something with `number` */
} catch (NumberFormatException e) {
System.err.println("Not a double.");
}
}

Categories