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* }
Related
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;
}
}
}
}
I am wishing to prompt the user again if a double outside of the accepted range (0-100) is input, until the input is valid. When the input is considered valid, I am wanting to return correct input value, yet, returned instead is the first incorrect value. How can I return the correct input, as accepted by the if statement?? Many thanks!
public class examscore {
public static void main (String[] args) {
Scanner console = new Scanner(System.in);
double sumfin = finalscore(console);
System.out.println(sumfin); // if user input is initially invalid, but then corrected, the first, incorrect, value is printed
}
public static double finalscore (Scanner console) {
System.out.println();
System.out.println("Input final exam score: ");
while(!console.hasNextDouble()) { //prompts the user, if invalid input, to input again, until a valid value is input
System.out.println("Please input a mark between 0 and 100. ");
console.next();
}
double examscore = console.nextDouble();
if (examscore >=0 && examscore<= 100) {
System.out.println();
System.out.println("Exam Score = "+examscore);
} else {
System.out.println("Error:");
finalscore (console);
}
return examscore; //an attempt to return the VALID exam score: fails
}
}
A do-while loop would be a perfect fit. Example:
Scanner console = new Scanner(System.in);
double userInput = 0;
do {
System.out.println("Please input a mark between 0 and 100. ");
try {
userInput = console.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Your input could not be interpreted as a floating-point number.");
}
} while (userInput <= 0D || userInput >= 100D);
You missed to assign result of finalscore(console) to examscore inside the else block.
if (examscore >= 0 && examscore <= 100) {
System.out.println();
System.out.println("Exam Score = " + examscore);
} else {
System.out.println("Error:");
examscore = finalscore(console);
}
You can either use a loop or a recursive call to accomplish this. I prefer a recursive call:
private static double getValidScore(Scanner console) {
System.out.println();
System.out.println("Input final exam score: ");
try {
double score = Double.parseDouble(console.nextLine());
if (score >= 0 && score <= 100) {
return score;
}
} catch (NumberFormatException nfe) {}
System.out.println("Please input a mark between 0 and 100.");
return getValidScore(console);
}
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;
}
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()
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I know these must be basic errors, but I'm not sure how to fix them.
I changed my class name to Interface & now Java has a problem with it.
Also, in my switch statement, I've tried to call the enterData method, but I'm getting an error on this line as well as on this line... "private static void enterData()" <-- it says a "token" is missing on this line?
I'm trying to call a method from case 0, but it isn't working.
import java.util.Scanner;
public class Interface {
private void run()
{
Scanner console = new Scanner(System.in);
Store store1 = new Store(); // MUST DO THIS
int demandRate, option, end;
double setupCost, unitCost, inventoryCost;
double sellingPrice, optimalOrder;
String name;
do {
System.out.println("Enter product data (0), Show product data (1), Show product strategy (2), Exit program (9).");
option = console.nextInt();
switch(option)
{
case 0: enterData();
break;
case 1:
break;
case 2:
break;
case 9: System.out.println("You chose to exit the program.");
break;
default: System.out.println("Please choose a valid option.");
}
} while (option != 9);
private static void enterData()
{
System.out.println("Product name between 3 & 10 characters long: ");
name = console.nextLine();
while ((name.length() < 3) || (name.length() > 10)) {
System.out.println("Please put in a name between 3 & 10 characters long.");
name = console.nextLine();
}
name = name.toLowerCase();
System.out.println("Demand rate: ");
demandRate = console.nextInt();
while (demandRate <= 0) {
System.out.println("Please put in a positive integer.");
demandRate = console.nextInt();
}
System.out.println("Setup cost: ");
setupCost = console.nextDouble();
while (setupCost <= 0) {
System.out.println("Please put in a positive number.");
setupCost = console.nextInt();
}
System.out.println("Unit cost: ");
unitCost = console.nextDouble();
while (unitCost <= 0) {
System.out.println("Please put in a positive number.");
unitCost = console.nextInt();
}
System.out.println("Inventory cost: ");
inventoryCost = console.nextDouble();
while (inventoryCost <= 0) {
System.out.println("Please put in a positive number.");
inventoryCost = console.nextInt();
}
System.out.println("Selling price: ");
sellingPrice = console.nextDouble();
while (sellingPrice <= 0) {
System.out.println("Please put in a positive integer.");
sellingPrice = console.nextInt();
}
}
}
public static void main(String[] args) {
Interface intFace = new Interface();
intFace.run();
}
}
You can't define method in another method.
Change your code to this:
public class Interface {
private void run()
{
Scanner console = new Scanner(System.in);
Store store1 = new Store(); // MUST DO THIS
int demandRate, option, end;
double setupCost, unitCost, inventoryCost;
double sellingPrice, optimalOrder;
String name;
do {
System.out.println("Enter product data (0), Show product data (1), Show product strategy (2), Exit program (9).");
option = console.nextInt();
switch(option)
{
case 0: enterData();
break;
case 1:
break;
case 2:
break;
case 9: System.out.println("You chose to exit the program.");
break;
default: System.out.println("Please choose a valid option.");
}
} while (option != 9);
}
private static void enterData()
{
int demandRate, option, end;
double setupCost, unitCost, inventoryCost;
double sellingPrice, optimalOrder;
Scanner console = new Scanner(System.in);
System.out.println("Product name between 3 & 10 characters long: ");
String name = console.nextLine();
while ((name.length() < 3) || (name.length() > 10)) {
System.out.println("Please put in a name between 3 & 10 characters long.");
name = console.nextLine();
}
name = name.toLowerCase();
System.out.println("Demand rate: ");
demandRate = console.nextInt();
while (demandRate <= 0) {
System.out.println("Please put in a positive integer.");
demandRate = console.nextInt();
}
System.out.println("Setup cost: ");
setupCost = console.nextDouble();
while (setupCost <= 0) {
System.out.println("Please put in a positive number.");
setupCost = console.nextInt();
}
System.out.println("Unit cost: ");
unitCost = console.nextDouble();
while (unitCost <= 0) {
System.out.println("Please put in a positive number.");
unitCost = console.nextInt();
}
System.out.println("Inventory cost: ");
inventoryCost = console.nextDouble();
while (inventoryCost <= 0) {
System.out.println("Please put in a positive number.");
inventoryCost = console.nextInt();
}
System.out.println("Selling price: ");
sellingPrice = console.nextDouble();
while (sellingPrice <= 0) {
System.out.println("Please put in a positive integer.");
sellingPrice = console.nextInt();
}
}
public static void main(String[] args) {
Interface intFace = new Interface();
intFace.run();
}
}
Try making a separate method and make those fields global. Something like this
import java.util.Scanner;
public class Interface {
int demandRate, option, end;
double setupCost, unitCost, inventoryCost;
double sellingPrice, optimalOrder;
String name;
private void run() {
Scanner console = new Scanner(System.in);
Store store1 = new Store(); // MUST DO THIS
do {
System.out
.println("Enter product data (0), Show product data (1), Show product strategy (2), Exit program (9).");
option = console.nextInt();
switch (option) {
case 0:
enterData(console);
break;
case 1:
break;
case 2:
break;
case 9:
System.out.println("You chose to exit the program.");
break;
default:
System.out.println("Please choose a valid option.");
}
} while (option != 9);
}
private void enterData(Scanner console) {
System.out.println("Product name between 3 & 10 characters long: ");
name = console.nextLine();
while ((name.length() < 3) || (name.length() > 10)) {
System.out
.println("Please put in a name between 3 & 10 characters long.");
name = console.nextLine();
}
name = name.toLowerCase();
System.out.println("Demand rate: ");
demandRate = console.nextInt();
while (demandRate <= 0) {
System.out.println("Please put in a positive integer.");
demandRate = console.nextInt();
}
System.out.println("Setup cost: ");
setupCost = console.nextDouble();
while (setupCost <= 0) {
System.out.println("Please put in a positive number.");
setupCost = console.nextInt();
}
System.out.println("Unit cost: ");
unitCost = console.nextDouble();
while (unitCost <= 0) {
System.out.println("Please put in a positive number.");
unitCost = console.nextInt();
}
System.out.println("Inventory cost: ");
inventoryCost = console.nextDouble();
while (inventoryCost <= 0) {
System.out.println("Please put in a positive number.");
inventoryCost = console.nextInt();
}
System.out.println("Selling price: ");
sellingPrice = console.nextDouble();
while (sellingPrice <= 0) {
System.out.println("Please put in a positive integer.");
sellingPrice = console.nextInt();
}
}
public static void main(String[] args) {
Interface intFace = new Interface();
intFace.run();
}
}
Interface is some kind of an abstract class definition keyword in java.
You can use a keyword to name your class with capitalized letters, but seriously, don't do this.
And you are not calling a method, you are implementing it in another method. You should go over writing and calling a method in java once again ;)