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.
Related
I need to write a program that calculates beverages for an entered amount of money. It was working before but I don't know if NetBeans just got tired of doing stuff or what because it suddenly couldn't get past the inputs. I can't figure out what I need to change to get it to function properly again and I can only assume it's the while loop that it's getting stuck on.
I have tried changing numbers, deleting spaces, altering the while conditions, moving line breaks around, and nothing works. Here is the official question:
Johnny is at the bar and he is going to drink beer.
Write a program that computes how many beers he can buy for money that he has. The program reads the amount and the price of beer, and prints how many beers he can afford. Consider also tax (10%) and tips (20%). Print the result in the following form: If a beer costs $3.25, Johnny can have 3 beers for $15 (he will pay $12.87).
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double br;
double amt;
double taxPrc;
double bill;
int count = 0;
System.out.printf("enter ur name: ");
String name = sc.nextLine();
System.out.printf("Enter price of beverage: $");
br = sc.nextDouble();
System.out.printf("Enter amt %s has: $", name);
amt = sc.nextDouble();
taxPrc = br * 1.1;
bill = taxPrc * 1.2;
while(bill<amt) {
count++;
bill = taxPrc * 1.2;
}
System.out.printf("if bevergae costs $"+br+", "+name+" can have "+count+" beverges for $"+amt+" (the bill will be $"+bill+").");
System.out.println();
}
My editor isn't showing that there are any problems. The file runs:
"enter ur name (name), Enter price of beverage $(#), Enter amt (name) has $(input number)"
then it just stops showing anything and leaves me on a blank until I stop it.
It's supposed to go on "if beverage costs $X, [name] can have [#] beverages for $[#] (the bill will be $[#])."
I was having an issues trying to get it to display the correct number for the bill less than the initial amount entered when it stopped working.
Just think about this block of code on its own for a bit
bill = taxPrc * 1.2;
while(bill<amt) {
count++;
bill = taxPrc * 1.2;
}
?
What in the while loop changes either bill or amt? Remember, a while loop runs until something in its conditional statement (in this case bill<amt) changes. As nothing in the while loop changes anything in the condition statement, it runs forever.
Your code doesn't change amt at all and just keeps resetting bill to the same value.
This program will calculate the amortization table for a user. The problem is my assignment requires use of subroutines. I totally forgot about that, any ideas on how to modify this to include subroutines?
public class Summ {
public static void main(String args[]){
double loanamount, monthlypay, annualinterest, monthlyinterest, loanlength; //initialize variables
Scanner stdin = new Scanner (System.in); //create scanner
System.out.println("Please enter your loan amount.");
loanamount = stdin.nextDouble(); // Stores the total loan amount to be payed off
System.out.println("Please enter your monthly payments towards the loan.");
monthlypay = stdin.nextDouble(); //Stores the amount the user pays towards the loan each month
System.out.println("Please enter your annual interest.");
annualinterest = stdin.nextDouble(); //Stores the annual interest
System.out.println("please enter the length of the loan, in months.");
loanlength = stdin.nextDouble(); //Stores the length of the loan in months
monthlyinterest = annualinterest/1200; //Calculates the monthly interest
System.out.println("Payment Number\t\tInterest\t\tPrincipal\t\tEnding Balance"); //Creates the header
double interest, principal; //initialize variables
int i;
/* for loop prints out the interest, principal, and ending
* balance for each month. Works by calculating each,
* printing out that month, then calculating the next month,
* and so on.
*/
for (i = 1; i <= loanlength; i++) {
interest = monthlyinterest * loanamount;
principal = monthlypay - interest;
loanamount = loanamount - principal;
System.out.println(i + "\t\t" + interest
+ "\t\t" + "$" + principal + "\t\t" + "$" + loanamount);
}
}
}
any ideas on how to modify this to include subroutines?
Well, you are better off doing it the other way around; i.e. working out what the methods need to be before you write the code.
What you are doing is a form or code refactoring. Here's an informal recipe for doing it.
Examine code to find a sections that perform a specific task and produces a single result. If you can think of a simple name that reflects what the task does, that it a good sign. If the task has few dependencies on the local variables where it currently "sits" that is also a good sign.
Write a method declaration with arguments to pass in the variable values, and a result type to return the result.
Copy the existing statements that do the task into the method.
Adjust the new method body so that references to local variables from the old context are replaced with references to the corresponding arguments.
Deal with the returned value.
Rewrite the original statements as a call to your new method.
Repeat.
An IDE like Eclipse can take care of much of the manual work of refactoring.
However, the real skill is in deciding the best way to separate a "lump" of code into discrete tasks; i.e. a way that will make sense to someone who has to read / understand your code. That comes with experience. And an IDE can't make those decisions for you.
(And did I say that it is easier to design / implement the methods from the start?)
I deleted my previous comment as I answered my own question by reading the associated tags :-)
As an example, define a method like this in your class:
public double CalculateInterest(double loanAmount, double interestRate) {
//do the calculation here ...
}
And then call the method by name elsewhere in your class code e.g.
double amount = CalculateInterest(5500, 4.7);
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.
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));
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.