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);
}
Related
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);
To be more clear, please assist me with menuChoice == 2.
I've gotten to the point where if you enter negative values, it prompts you to enter again until it's positive and then the calculations come out fine. However, when I enter just positive values now, it doesn't calculate anything. I've been trying for a while but I just can't figure it out.
What do I need to do?
package finalExam;
//this is required for JOptionPane to work
import javax.swing.JOptionPane;
public class Geometry {
public static void main(String[] args) {
boolean valid = false;
int menuChoice;
do {
// create a menu and display it to the user
// then ask the user to choose an option
String menu = "1) Calculate the area of a circle\n"
+ "2) Calculate the area of a rectangle\n"
+ "3) Calculate the area of a triangle\n"
+ "4) Quit\n"
+ "Please enter your choice: (1, 2, 3, or 4)";
menuChoice = Integer.parseInt(JOptionPane.showInputDialog(menu));
if(menuChoice == 1)
{
String unknownRadius = JOptionPane.showInputDialog("What is the radius of the circle?");
if(Double.parseDouble(unknownRadius) < 0){
do{
JOptionPane.showMessageDialog(null, "Please enter positive numbers only.");
unknownRadius = JOptionPane.showInputDialog("What is the radius of the circle?");
}
while(Double.parseDouble(unknownRadius) < 0);
double knownRadius = Double.parseDouble(unknownRadius);
double circleArea = Math.pow(knownRadius, 2) * 3.14159;
JOptionPane.showMessageDialog(null, "The area of the circle is " + circleArea);
}
else if(Double.parseDouble(unknownRadius) > 0) {
double knownRadius = Double.parseDouble(unknownRadius);
double circleArea = Math.pow(knownRadius, 2) * 3.14159;
JOptionPane.showMessageDialog(null, "The area of the circle is " + circleArea);
valid = true;
}
} else if(menuChoice == 2){
String unknownLength = JOptionPane.showInputDialog("What is the length of the rectangle?");
if(Double.parseDouble(unknownLength) < 0){
do{
JOptionPane.showMessageDialog(null, "Please enter positive numbers only.");
unknownLength = JOptionPane.showInputDialog("What is the length of the rectangle?");
}
while(Double.parseDouble(unknownLength) < 0);
double knownLength = Double.parseDouble(unknownLength);
String unknownWidth = JOptionPane.showInputDialog("What is the width of the rectangle?");
if(Double.parseDouble(unknownWidth) < 0){
do{
JOptionPane.showMessageDialog(null, "Please enter positive numbers only.");
unknownWidth = JOptionPane.showInputDialog("What is the width of the rectangle?");
}
while(Double.parseDouble(unknownWidth) < 0);
double knownWidth = Double.parseDouble(unknownWidth);
double rectangleArea = knownLength * knownWidth;
JOptionPane.showMessageDialog(null, "The area of the rectangle is " + rectangleArea);
}
else if(Double.parseDouble(unknownLength) > 0){
knownLength = Double.parseDouble(unknownLength);
unknownWidth = JOptionPane.showInputDialog("What is the width of the rectangle?");
if(Double.parseDouble(unknownWidth) > 0) {
double knownWidth = Double.parseDouble(unknownWidth);
double rectangleArea = knownLength * knownWidth;
JOptionPane.showMessageDialog(null, "The area of the rectangle is " + rectangleArea);
valid = true;
}
}
}
} else if(menuChoice == 3){
String unknownBase = JOptionPane.showInputDialog("What is the base length of the triangle?");
if(Double.parseDouble(unknownBase) > 0){
double knownBase = Double.parseDouble(unknownBase);
String unknownHeight = JOptionPane.showInputDialog("What is the height of the triangle?");
if(Double.parseDouble(unknownHeight) > 0){
double knownHeight = Double.parseDouble(unknownHeight);
double triangleArea = (knownBase / 2) * knownHeight;
JOptionPane.showMessageDialog(null, "The area of the triangle is " + triangleArea);
valid = true;
}
else { JOptionPane.showMessageDialog(null, "Please enter a positive number");
JOptionPane.showInputDialog("What is the base length of the triangle?");
}
}
else { JOptionPane.showMessageDialog(null, "Please enter a positive number");
JOptionPane.showInputDialog("What is the height of the triangle?");
}
}else if(menuChoice == 4){
System.exit(0);
} else
JOptionPane.showMessageDialog(null, "Please select from the options given (1-4)!");
}
while(!valid || menuChoice != 4);
}
}
On line 48, your statement if(Double.parseDouble(unknownLength) < 0){ has the matching closing brace is on line 76, just before the } else if(menuChoice == 3){.
So, logically your code is only running the menuChoice == 2 section when a negative number is entered. You should instead close the if after the first do-while loop completes, since at that point the number will have been (corrected to) positive.
You should also try to work on formatting your code. It will make it more readable and you can easily see that the braces don't line up where they should have after using a beautifier tool, such as Tutorial Point Online Java Formatter.
You've made things too complicated for yourself by having two different blocks of code depending on whether the first length is negative or positive. Basically, your code looks like:
If the length is negative then {
Ask for a new length until it's positive
Now input the width, reject negative values, do the computation,
and output it
} else { // the length is positive
Input the width, reject negative values, do the computation,
and output it
}
The whole part about handling the width occurs twice in your code, which makes the code needlessly complex, and makes it more prone to errors such as getting the curly braces in the wrong place (which I think is why the code isn't behaving). You can make life a lot simpler for yourself by reorganizing the code like this:
If the length is negative then {
Ask for a new length until it's positive
}
// When we get here, the length will be positive. It doesn't matter
// whether we got here because the original length was positive, or whether
// it was negative and the user entered a new value. We're going to
// continue in the same way, either way.
Input the width, reject negative values, do the computation,
and output it
(By the way, I don't know what you want to do if the user enters 0. You really aren't handling that case.)
As far as I could understand, if I have to just achieve what you are asking in the question ,I could simply do like.
(I am giving just an alternate code here in JAVA , you can modify your Japplet accordingly)
int a=-1,b=-1;
a=sc.nextInt();
b=sc.nextInt();
if(a>=0 && b>=0){
...
//do the task
}
else{
while(a<0 || b<0){
System.out.println("negative value not allowed, enter +ve value ");
a=sc.nextInt();
b=sc.nextInt();
}
// while exited only if value both a and b are positive
//+ve value
//perform task
}
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.
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;
My code is supposed to simulate something similar to a vending machine. But there is a problem when I enter a price that is not one of my options, e.g. 0.82 the program still runs. How do I get it to only accept one of my options?
import java.util.Scanner;
public class VendingMachine
{
public static void main (String[] args)
{
double price;
Scanner keyboard = new Scanner(System.in);
System.out.println("Choose your price. Your options are: ");
double i;
for (i=0.25; i<=1.25; i+=0.25)
System.out.printf("$%.2f\n", i );
System.out.println("Enter your selection now: ");
price=keyboard.nextDouble();
System.out.printf("You chose the $%.2f option. ",price);
double deposit;
if (price<=1.00) {
System.out.println("Please insert 1 dollar. *This machine only accepts Loonies*");
deposit=1;
} else {
System.out.println("Please insert 2 dollars.*This machine only accepts Loonies*");
deposit=2;
}
System.out.println("Please press 'Enter' to simulate inserting money. ");
new Scanner(System.in).nextLine();
double change;
change = deposit-price;
System.out.printf("Your change is $%.2f\n",change);
}
}
I tried something like this but it doesn't work. What is the best way to do this.
if (price==i)
System.out.println("You entered " + price);
else {
System.out.println("Invalide choice. Please try again.")
System.exit(0);
}
Here is an image if you find it easier to read.
You can use some sort of loop (while, do-while, for), which will continue to excecute the code until a condition is (or isn't) met.
Here is an example:
do {
code line 1;
code line 2;
code line 3;
...
} while(yourCondition);
If yourCondition is satisfied (yourCondition == true), the code will go back to code line 1 (will perform the code block between do and while) and it'll stop once the condition isn't satisfied(yourCondition == false). yourCondition could be any expression that returns a true/false result (boolean), such as 2+2==4.
If you want to keep looping for as long as yourCondition isn't met, you can add a ! before your expression, which will evaluate the opposite of your boolean like this (!yourCondition).
Now, if you understood how that works, you can easily apply it to your code.
If you want the user to enter only your displayed prices, I suggest the following, you shall edit to your exact desires.
//given you an open scanner
boolean isCorrectPrice = false;
System.out.println("enter price");
price = in.nextDouble();
while(!isCorrectPrice)
{
if(price%0.25==0 && price<=1.25 && price>0)
{
System.out.println("you entered "+price);
IsCorrectPrice = true;
continue;
}
System.out.println("incorrect price, re-enter ");
price = in.nextDouble();
}
//your code after user enters correct price
That will do the check. If your prices change, all you have to do is change the maximum price provided its still dividable with 0.25 or the condition price check.
Use BigDecimal (instead of double) to work with money. Its exact -- double isn't.
http://docs.oracle.com/javase/6/docs/api/java/math/BigDecimal.html
I would write a function to get the user input. It would not return until the
user had entered an allowed value.
Although my real answer is the one on the comments, you can use something like this. To check recursively if the correct value was given.
import java.util.Scanner;
public class VendingMachine {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Choose your price. Your options are: ");
for (double i = 0.25; i <= 1.25; i += 0.25) {
System.out.printf("$%.2f\n", i);
}
double price = checkMultipleValues(0.25,1.25, 0.25);
System.out.printf("You chose the $%.2f option. ", price);
double deposit;
if (price <= 1.00) {
System.out.println("Please insert 1 dollar. *This machine only accepts Loonies*");
deposit = 1;
} else {
System.out.println("Please insert 2 dollars.*This machine only accepts Loonies*");
deposit = 2;
}
System.out.println("Please press 'Enter' to simulate inserting money. ");
new Scanner(System.in).nextLine();
double change;
change = deposit - price;
System.out.printf("Your change is $%.2f\n", change);
}
private static double checkMultipleValues(double initial,double last,double step) {
System.out.println("Enter your selection now: ");
double price = keyboard.nextDouble();
for (double i = initial; i <= last; i += step) {
if (price == i) {
return price;
}
}
return checkMultipleValues( initial, last, step);
}
}
ADDENDUM
Since you like #Sello answer why don't you combine it with #MrD and have something like
do {
System.out.println("enter price");
price = in.nextDouble();
// System.out.println("you entered " + price);
} while (!(price % 0.25 == 0 && price <= 1.25 && price > 0));