Converting measurements in Java [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
So in my homework I need to write a program that asks for the users height and weight and convert it from feet, inches to meters, cm. As well as convert the weight from pounds to kilograms. The program I've got would not be able to take a measurement such as 5'7 and convert it.
Here is the acutual homework question:
The program asks the name of the user. The program will prompt "What is your name?" the user types his/her name.
The program should then ask for height and weight of the user.
It should then print on separate lines, "Name of the User" your height in metric system is (prints out the height in Meters and cm. For example, your height in metric system is 1 meter 45 cm.
It should then print the weight in KG and grams (same as above your weight in metric system is ----)
Here is what I have come up with thus far:
package extracredit;
/**
*
* #author Kent
*/
import java.util.Scanner;
public class Extracredit {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("What is your name? ");
String name = in.next();
System.out.println("What is your height? ");
Double Height = in.nextDouble();
System.out.println("What is your weight? ");
Double Weight = in.nextDouble();
System.out.println(name);
System.out.print("Your height in metric system: ");
System.out.println(Height * .3048);
System.out.println("Your weight in kg: ");
System.out.println(Weight*0.453592);
}
}

The simple solution is this.
You ask "what is your height in feet", let that be int feet.
Then "and how many inches", let that be int inches.
Then assign int totalInches = 12*feet + inches.
Other solutions would include splitting the string on the ' character and parsing the intvalues out.
Or using a regular expression, but I'm guessing that would be a more advanced topic than you are seeking at the moment.

You could try this approach, it will ask for the height in the feet'inches" format and then convert it to inches/centimetres.
Scanner in = new Scanner(System.in);
System.out.println("Please enter your height (feet'inches\")");
String heightInput=in.next();
int heightInInches;
heightInInches=Integer.parseInt(heightInput.split("'")[0])*12;
//Calculate feet
heightInInches+=Integer.parseInt(heightInput.split("'")[1].replaceAll("[^\\d.]",""));
//Celculate remaining inches, regex is used to remove the "
System.out.println("Height in inches: "+heightInInches);
System.out.println("Height in centimetres: "+heightInInches*2.54);
//Multiply by 2.54 to convert to centimetres

If you are accepting formatted input then you should likely use an explicit regular expression with groups to represent the values. That way you get all the error checking for free as part of the parsing.
For example:
Pattern heightPattern = Pattern.compile("(\\d+)'(\\d+)\"");
Matcher heightMatcher = heightPattern.match(in.next());
while (!heightMatcher.matches()) {
System.out.println("Please re-enter your height in the format n'n\"");
heightMatcher = heightPattern.match(in.next());
}
int feet = Integer.valueOf(heightMatcher.group(1));
int inches = Integer.valueOf(heightMatcher.group(2));

You could just get the input as a String and split it like
String height = in.next();
String[] splitHeight = height.split("'");
int feet = Integer.valueOf(splitHeight[0]);
int inches = Integer.valueOf(splitHeight[1]);
Here you'd have to consider that splitHeight[1] might be null (if the input String does not contain a ' ).
Afterwards you can just do your calculations in inches with feet * 12 + inches.

Related

Few days in and looking for efficiency advice [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Im a few days into learning Java (My first language) and im just wondering if there is a more efficient way of writing this code?
Main goal of the program is to calculate someones BMI.
It asks a user for their name, asks if they'd like to use Metric or Imperial, asks for the measurements and provides the answer with a small chart for the user to see where they fit.
It works fine at the moment but im trying to figure out ways to condense the code and make it more efficient (purely for learning purposes)
import java.util.Scanner; //importing the java library utilities to use the scan functions
public class Bmi0 //declaring my intitial class and making it a public class
{
public static void main(String[] args) //my main method
{
Scanner input = new Scanner(System.in); // starts the scanner utility to take input fromm the command line
float height; //declaring a variable
float weight; //declaring a variable
float bmi; //declaring a variable
String option; //declaring a variable
String name; //declaration of a variable called name of type string
System.out.printf("%nWhat is your name? ");//prompts the user for their name
name = input.nextLine(); //reads the users input and saves it to the variable name
System.out.printf("%nHi %s, Let's calculate you BMI %n" , name); //displays what the user
//typed using a %s as the place holder for the value that is in the name variable
System.out.printf("%nUse Imperial or Metric? (Format: I or M) "); //printing to the command window and asking for input
option = input.nextLine(); //placing the user input into the height variable
if (option.equals ("M")) //if option is M for metric do the following
{
System.out.printf("%nWhat is your height in Meters? "); //printing to the command window and asking for input
height = input.nextFloat(); //placing the user input into the height variable
System.out.print("What is your weight in Kilos? "); //printing to the command window and asking for input
weight = input.nextFloat(); //placing the user input into the weight variable
bmi = (weight / (height * height)); //calculates the conversion and stores it in the variable
System.out.printf("%nOk %s, your BMI is: %.2f%n%n" , name, bmi); //displays the answer to 2 decimal places
System.out.printf("BMI Categories:%n Underweight = <18.5 %n Normal weight = 18.5 - 24.9 %n Overweight = 25 - 29.9 %n Obesity = BMI of 30 or greater %n%n%n");
}
else if (option.equals ("I")) //if the imperial option is chosen
{
System.out.printf("%nWhat is your height in Inches? "); //printing to the command window and asking for input
height = input.nextFloat(); //placing the user input into the height variable
System.out.printf("What is your weight in Pounds? "); //printing to the command window and asking for input
weight = input.nextFloat(); //placing the user input into the weight variable
bmi = (weight / (height * height) * 703) ; //calculates the conversion and stores it in the variable
System.out.printf("%nOk %s, your BMI is: %.2f%n%n" , name, bmi); //displays the answer to 2 decimal places
System.out.printf("BMI Categories:%n Underweight = <18.5 %n Normal weight = 18.5 - 24.9 %n Overweight = 25 - 29.9 %n Obesity = BMI of 30 or greater %n%n%n");
}
} //end of the method
}//end of the class
A few thoughts:
too many comments. //importing the java library utilities to use the scan functions ... that doesn't tell the reader anything that import java.util.Scanner doesn't already give away. Too much information in code is counter productive. It makes the reader waste his time and energy on details that don't matter. Instead: write your code in ways that make its intention clear, without the need of extensive comments.
formatting: follow the standard java coding style guides. Like: keep the opening { on the line of the if condition for example. Do not add another empty line after the brace. Instead, indent the new block with 2 or 4 spaces. One pretty famous approach right now is the one from google.
Your code is "okay" for a new newbie, but as said: most of the comments could be thrown out, and that would improve readability. The next improvement would be to put the different "aspects" into smaller helper methods, to avoid having everything in one lengthy main method.

Why is this error coming up when I try to get double to 2 decimal places [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
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.
Improve this question
I am creating a simple program to calculate the cost of running a car. The program works just fine but I wanted to see if I could get the final answer to 2 decimal places. I tried using the '%8.2f' thing but it said that no method could be found for println(string, double)
This is my code:
/* Program to calculate the running cost of car */
import java.util.Scanner;
public class RunningCosts {
public static void main(String[] args) {
final int TOTAL_DISTANCE = 100000;
Scanner in = new Scanner(System.in);
System.out.print("Enter the car cost: ");
double carCost = in.nextDouble();
System.out.print("Enter the service cost: ");
double serviceCost = in.nextDouble();
System.out.print("Enter the service interval: ");
double serviceInterval = in.nextDouble();
System.out.print("Enter km per litre: ");
double kmPerLitre = in.nextDouble();
System.out.print("Enter the fuel cost per litre: ");
double fuelCostPerLitre = in.nextDouble();
double serviceTotal = (TOTAL_DISTANCE/serviceInterval) * serviceCost;
System.out.println( "Service Total: " + serviceTotal); //Here
double fuelCost = (TOTAL_DISTANCE/kmPerLitre) * fuelCostPerLitre;
System.out.println( "Fuel Cost: " + fuelCost); //Here
double totalCost = carCost + fuelCost + serviceTotal;
System.out.println( "Estimated Cost: " + totalCost); //And here
}
}
The commented lines are what I would like to be formatted to 2 decimal places
Either use printf as #shmosel suggested, or use String.format:
System.out.println( "Service Total: " + String.format("%.2f", serviceTotal));
See this page for more usage examples.

how to Calculate speed and distance traveled in Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
how do you write a program that prompts for and reads integer values for speed and distance traveled, then prints the time required for the trip as a floating point result in java using eclipse
import java.util.Scanner;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Lab3 {
public static void main(String[] args) {
int time = 0;
int distance = 0;
int speed = distance/time;
float fval = speed * time;
double dval = distance/speed;
String message;
Scanner scan = new Scanner(System.in);
System.out.println("Please Enter Your Avaerage Speed: ");
message = scan.nextLine();
System.out.println("You Entered: \"" + message + "\"");
System.out.println("Your Total Speed is: ");
Here are some hints:
You haven't finished your code.
You need a closing } for each {.
Include the value you want to output here:
System.out.println("Your Total Speed is: ");
Hint: the string concatenation operator is .... ?
Hint: you can't calculate the speed before you know what the distance and time values are. speed = distance/time; is an assignment statement, not an equation.
it's crashing. My console isn't able to take data or input
The code you showed us doesn't compile. You can't run it ... so it can't be crashing. Hint: show us the real code. All of it.
If it is crashing, then there must be a stacktrace. The stacktrace contains important information that will help us (and you) identify the cause of the problem. Put all important information into the Question. Use the Edit button.
My guess is that an ArithmeticException is being thrown here
int speed = distance/time;
because you are dividing by zero. You are dividing by zero, because on the line before you set time to zero. Explicitly.
Please read what I wrote above ("4. Hint: ...") about not doing calculations before you have the inputs.
package stackoverflow;
import java.util.Scanner;
public class Lab3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please Enter speed: ");
int speed = in.nextInt();
System.out.print("Please Enter distance: ");
int distance = in.nextInt();
float time = (float)distance / speed;
System.out.println("Your time is: " + time);
}
}

Can't understand this scanner or addition command

I'm very new to Java and don't quite understand it all fully, I'm working on a Uni workshop assignment but am having trouble with this particular question.
"Write a program that asks the user to enter how many minutes they have used, and how many texts they have used.
Both inputs should be whole numbers (integers).
The program should then calculate the user’s mobile phone bill, assuming that texts cost 7p and calls 12p.
Should display price of calls, texts and the total bill, both figures added together"
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
String one = userInput.nextLine();
System.out.println("How many texts have you used?");
String two = userInput.nextLine();
int a = 12;
int b = 7;
System.out.println("The total cost of your minutes is "+one);
System.out.println("The total cost of you texts is "+two);
System.out.println("The total cost of your phone bill is "+one + two);
I have the basic part to the question figured out, but can't figure out why I can't add to the code for it to figure out the price, being 12 p for minutes, and 7p for texts. As well as this I can't get the total cost of the phone bill to add together correctly. I did earlier and I know it's very easy, but I've completely forgotten how to do it.
I know I need to be able to understand a scanner better, but I did the previous tasks easy enough but this has really stumped me tbh. Do I need to rename the scanner, but when I change the name of the integer line to something like "totalCostOfTexts/Minutes etc" it either says it has already been defined, or is missing some kind of symbol.
Any feedback is appreciated.
I add the code :
int = userInput = minutes * 12:
As that's what is used in the previous part of a similar question, but all the feedback I get is that it is not a statement, so it can't process. I'm really struggling with this tbh.
Following code will work for you
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
int one = userInput.nextInt();
System.out.println("How many texts have you used?");
int two = userInput.nextInt();
int a = 12; //don't use such variable names
int b = 7;
int minute_bill=12*a; //see the variable,will make things easier to review
int text_bill=7*b;
int result=minute_bill+text_bill;
System.out.println("The total cost of your minutes is "+minute_bill);
System.out.println("The total cost of you texts is "+ text_bill);
System.out.println("The total cost of your phone bill is "+result);
and also
You can use Scanner's nextInt() method for taking integer input
from console.
Don't use such variable names like a,b etc. define them according to the attribute whose value you are storing in them (see above minute_bill and text_bill are making the code clean and easy to review)
And if you are bound to get String value from console,but want to convert entered value to Integer later on, then you can do it like following code
String mystring=userInput.nextLine(); //userInput is user Scanner's object
int num=Integer.parseInt(mystring);
I think this is what you want to do...
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
int one = Integer.valueOf(userInput.nextLine());
System.out.println("How many texts have you used?");
int two= Integer.valueOf(userInput.nextLine());
int a = 12;
int b = 7;
System.out.println("The total cost of your minutes is "+ (one * 12);
System.out.println("The total cost of you texts is "+ (two * 7));
System.out.println("The total cost of your phone bill is "+ ((one * 12) + (two * 7));

no matter what the user inputs the output stays at 2000 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
1) Change the program so that the user has to enter the initial balance and the interest rate. Assume that the user will enter interest rates in whole numbers ("5" would represent an interest rate of 5%, for example). Assume that the user will enter initial balances that are numeric only - no commas. 2) Change the code to display how many years it takes an investment to triple.
I have entered my scanner so the user can input their balance and interest. no matter what user enters it outputs 2000.
import java.util.Scanner;
public class InvestmentRunner
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please Enter Initial Balance:");
String Balance = in.next();
System.out.print("Please Enter Interest Rate:");
String Interest = in.next();
final double INITIAL_BALANCE = 10000;
final double RATE = 5;
Investment invest = new Investment(INITIAL_BALANCE, RATE);
invest.waitForBalance(2 * INITIAL_BALANCE);
int years = invest.getYears();
System.out.println("The investment doubled after "
+ years + " years");
}
}
Per the question askers comment: well no matter what the user inputs the output stays at 2000
These are the lines in which you're constructing an Investment object, calling methods on this object, and then printing the value.
Investment invest = new Investment(INITIAL_BALANCE, RATE);
invest.waitForBalance(2 * INITIAL_BALANCE);
int years = invest.getYears();
System.out.println("The investment doubled after " + years + " years");
You haven't posted the Investment class, so I just have to assume these methods are fine. The PROBLEM is here:
final double INITIAL_BALANCE = 10000;
final double RATE = 5;
These are the variables you're sending to the Investment constructor. Constants you've hardcoded in. Meanwhile, this is where you take user input:
System.out.print("Please Enter Initial Balance:");
String Balance = in.next();
System.out.print("Please Enter Interest Rate:");
String Interest = in.next();
You take the Balance (should be balance), then take Interest (should be interest), then you do nothing with these values. You need to parse a double out of these Strings and then send them as the arguments to your constructor.

Categories