fix me plz. i get multiple error messages
"variable airSpeed_km might not have been initialized"
"variable width might not have been initialized"
"variable length might not have been initialized"
import java.util.Scanner;
public class V4_________1{
public static void main (String args[])
{
Scanner keyboard = new Scanner(System.in);
double KNOTS_TO_KMPHR;
double airSpeed_km;
double airSpeed_knots;
double width;
double length;
***// need to do something in the main but not sure what exactly***
airSpeed_knots = keyboard.nextDouble();
System.out.println("what is your current airspeed in knots?");
System.out.println("your current airspeed in km is: " + airSpeed_km + "your holding pattern width is: " + width + "your holding patter length is: " + length);
}
public static double getAirSpeed(double airSpeed_knots, double KNOTS_TO_KMPHR, double airSpeed_km)
{
KNOTS_TO_KMPHR = 1.852;
airSpeed_km = airSpeed_knots * KNOTS_TO_KMPHR ;
return airSpeed_km;
}
public static double calcPatternWidth(double width, double airSpeed_km)
{
width = (airSpeed_km) / (60 * Math.PI) * 2;
return width;
}
public static double calcPatternLength(double airSpeed_km, double length)
{
length = (airSpeed_km) / (60 * Math.PI) * 2 + ((airSpeed_km) / 60);
return length;
}
}
You declare:
double airSpeed_km;
And after use it:
System.out.println("your current airspeed in km is: " + airSpeed_km + "your holding pattern width is: " + width + "your holding patter length is: " + length);
without any assignment. So you get an error, you can prevent this by giving it a default value of 0 for example.
double airSpeed_km = 0;
(same goes for your other errors)
In Java, the compiler gets upset if a variable even MIGHT be used without a value.
So it is best practice to always give a value to variables when you first declare them.
Since you normally don't know the value a variable will have at the time of declaration, it is common practice to give it a value of zero.
So your declarations should look like this:
double KNOTS_TO_KMPHR=0;
double airSpeed_km=0;
double airSpeed_knots=0;
double width=0;
double length=0;
This will take care of all your "[] might not have been initialized" compiler errors.
Your code is in correct. Your cannot set variable when you pass them into a function. See both approaches and understand what going on.
You can do this:
public static void main (String args[])
{
Scanner keyboard = new Scanner(System.in);
double KNOTS_TO_KMPHR=1.852;
double airSpeed_knots;
System.out.println("what is your current airspeed in knots?");
airSpeed_knots = keyboard.nextDouble();
System.out.println("your current airspeed in km is: " + getAirSpeed(airSpeed_knots) + "your holding pattern width is: " + calcPatternWidth(getAirSpeed(airSpeed_knots)) + "your holding patter length is: " + calcPatternLength(getAirSpeed(airSpeed_knots));
}
public static double getAirSpeed(double airSpeed_knots)
{
return airSpeed_knots * KNOTS_TO_KMPHR ;
}
public static double calcPatternWidth(double airSpeed_km)
{
return (airSpeed_km) / (60 * Math.PI) * 2;
}
public static double calcPatternLength(double airSpeed_km)
{
return (airSpeed_km) / (60 * Math.PI) * 2 + ((airSpeed_km) / 60);
}
Or do this if you want to set variables:
public static void main (String args[])
{
Scanner keyboard = new Scanner(System.in);
double KNOTS_TO_KMPHR=1.852;
double airSpeed_knots;
System.out.println("what is your current airspeed in knots?");
airSpeed_knots = keyboard.nextDouble();
double airSpeed_km=getAirSpeed(airSpeed_knots);
double width=calcPatternWidth(airSpeed_km);
double length= calcPatternLength(airSpeed_km);
System.out.println("your current airspeed in km is: " + airSpeed_km + "your holding pattern width is: " + width + "your holding patter length is: " + length);
}
public static double getAirSpeed(double airSpeed_knots)
{
return airSpeed_knots * KNOTS_TO_KMPHR ;
}
public static double calcPatternWidth(double airSpeed_km)
{
return (airSpeed_km) / (60 * Math.PI) * 2;
}
public static double calcPatternLength(double airSpeed_km)
{
return (airSpeed_km) / (60 * Math.PI) * 2 + ((airSpeed_km) / 60);
}
Related
I have been trying to make a program that takes in:
Initial Value (in billions)
Growth Rate / Year (in billions)
Purchase Price (in billions)
And then is able to calculate the number of years it would take to break even on the investment. I have been able to accomplish this with a brute force algorithm.
I was wondering if there was a way to do this more efficiently (in a way that is more similar to standard algebra).
My Code:
import java.util.Scanner;
public class ReturnOnInvestment {
public static double initialValue;
public static double growthRate;
public static double purchasePrice;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" Return on Investment Calculator ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.print(" Starting Value (In Billions): ");
initialValue = input.nextDouble();
System.out.print(" Growth Rate (Per Year in Billions): ");
growthRate = input.nextDouble();
System.out.print(" Purchase Price (In Billions): ");
purchasePrice = input.nextDouble();
input.close();
System.out.println("-----------------------------------------");
System.out.println(" ROI Period: " + calculateYears(0) + " Years");
}
public static double calculateMoney(double years) {
if(years < 1) return 0;
return calculateMoney(years - 1) + initialValue + (growthRate * (years - 1));
}
public static double calculateYears(double years) {
if(calculateMoney(years) >= purchasePrice) return Math.round(years * 100) / 100.0;
return calculateYears(years + 0.01);
}
}
Yes - you can use the logarithm function for that.
Given your Java code you can write:
public static double yearsNeeded(double initialValue, double growthRate, double purchasePrice) {
return Math.log(purchasePrice / initialValue) / Math.log(1 + growthRate);
}
with an example:
public static void main(String[] args) {
System.out.println("Years to go from 100 to 150 with a growth rate of 5%: "
+ yearsNeeded(100, .05, 150));
}
Basically you're trying to solve for "years":
initialValue * (1 + growthRate) ^ years = purchasePrice
where ^ means exponentiation.
You can rewrite that to:
(1 + growthRate) ^ years = purchasePrice / initialValue
which turns into:
years = [1 + growthRate] log (purchasePrice / initialValue)
where the base of the log is "1 + growthRate". And a log of another base is the same as the log in any base divided by the log of the base.
import java.util.Scanner ;
public class CollinsHealthCalculator {
double ACTIVITY_FACTOR = 1.375;
public static void main (String[] args) {
newHealthCalcDescription ();
Scanner keyboard = new Scanner (System.in);
System.out.println ("What is your weight in pounds? ");
double weightlb = keyboard.nextDouble ();
System.out.println ("What is your height in inches? ");
double heightin = keyboard.nextDouble ();
System.out.println ("What is your age in years? ");
double ageYears = keyboard.nextDouble ();
double WEIGHT_KILOGRAMS = weightlb / 2.2;
double HEIGHT_METERS = heightin * .0254;
double weightkg = WEIGHT_KILOGRAMS;
double heightm = HEIGHT_METERS;
double computingBMI (BMI, weightkg, heightm);
maleBMR (heightm, weightkg, ageYears);
femaleBMR (heightm, weightkg, ageYears);
showResults (BMI, caloriesm, caloriesf);
public static newHealthCalcDescription () {
System.out.println("This calculator will determine your BMI "
+ "(Body Mass Index). While also it will determine the amount "
+ "of calories needed to maintain weight.");
}
//Computing the BMI
public static void computingBMI (double BMI, double weightkg, double heightm){
BMI = weightkg/(Math.pow(heightm, 2));
}
//Computing BMR for male and female
public static void maleBMR (double heightm, double weightkg, double ageYears) {
double HEIGHT_CENTIMETERS = heightm * 100;
double heightcm = HEIGHT_CENTIMETERS ;
double BMRForMales = 13.397 * weightkg + 4.799 * heightcm - 5.677 * ageYears + 88.362;
double caloriesm = Math.round(BMRForMales * 1.375);
}
public static void femaleBMR (double heightm, double weightkg, double ageYears) {
double HEIGHT_CENTIMETERS = heightm * 100;
double heightcm = HEIGHT_CENTIMETERS ;
double BMRForFemales = 9.247 * weightkg + 3.098 * heightcm - 4.330 * ageYears + 447.593;
double caloriesf = Math.round(BMRForFemales * 1.375);
}
public static void showResults (double BMI, double caloriesm, double caloriesf) {
//Show results
System.out.printf ("%nYour BMI is: %7.1f", BMI);
System.out.println ("A BMI between 18.5 to 24.9 is considered normal.");
System.out.println ();
System.out.println ("To maintain current weight:");
System.out.print ("Men need to eat " + caloriesm);
System.out.println (" calories per day.");
System.out.print ("Females need to eat " + caloriesf);
System.out.println (" calories per day.");
}
}
I'm trying to get the code to pass down statements but I'm new to programming and have no clue on how to go about getting method passed down to another method. I've tried researching everywhere but I've had little luck in finding any help. Please help so I can make my programm functional I'm excited to learn just need help.
You can try giving the variables the global scope(outside the method). You may learn about it here.
When you declare a variable inside a method (i.e. code block), it is local to that block. So you cannot use that variable in any other method. Here the best option for you to do is to declare the variable, i.e. like weightkg etc as class variables.
You can change the return type of the methods from void to double and store the returned result and send the results to other methods.
for eg.
public static double computingBMI (double BMI, double weightkg, double heightm){
return weightkg/(Math.pow(heightm, 2));
}
I'm having a bit of an issue with a school project of mine. We're supposed to write a Loan class that will do things associated with, well, loans, such as return the monthly payment and the total payment on the loan. My problem is that I have specific instructions for this code that I absolutely cannot go outside of.
Here's the code:
import java.util.Scanner;
import java.text.DecimalFormat;
import java.lang.Math;
public class Loan
{
public double annualInterestRate = 0;
public int numberOfYears = 0;
public double loanAmount = 0;
public Loan()
{
annualInterestRate = 0.025;
numberOfYears = 1;
loanAmount = 1000;
}
public Loan(double interestRate, int numYears, double amount)
{
setRate(interestRate);
setYears(numYears);
setLoanAmount(amount);
}
public void setRate(double interest)
{
DecimalFormat percent = new DecimalFormat( "0.0%" );
if(interest > 25 || interest < 0)
{
System.out.println("WARNING: Invalid annual interest rate: " + percent.format(interest) + ".");
System.out.println("Current value not changed: " + percent.format(annualInterestRate * 100) + ".");
}
else
{
annualInterestRate = interest;
}
}
public void setYears(int years)
{
if(years > 30 || years <= 0)
{
System.out.println("WARNING: Invalid number of years: " + years + ".");
System.out.println("Current value not changed: " + numberOfYears + ".");
}
else
{
numberOfYears = years;
}
}
public void setLoanAmount(double amnt)
{
DecimalFormat loan = new DecimalFormat( "$#,##0.00" );
if(amnt <= 0)
{
System.out.println("WARNING: Invalid loan amount: " + loan.format(amnt) + ".");
System.out.println("Current value not changed: " + loan.format(amnt) + ".");
}
else
{
loanAmount = amnt;
}
}
public double getAnnualInterestRate()
{
return annualInterestRate;
}
public int getNumberOfYears()
{
return numberOfYears;
}
public double getLoanAmount()
{
return loanAmount;
}
public double getMonthlyPayment()
{
double monthly = annualInterestRate/12;
double monthlyPayment = (loanAmount * monthly)/1 - (1/(1 + monthly));
monthlyPayment = Math.pow(monthlyPayment, 12);
return monthlyPayment;
}
public double getTotalPayment()
{
double totalPayment = getmonthlyPayment() * 12;
return totalPayment;
}
public String toString()
{
DecimalFormat percent = new DecimalFormat( "0.0%" );
DecimalFormat loan = new DecimalFormat( "$#,##0.00" );
String interestRate = percent.format(annualInterestRate);
String numOfYears = Integer.toString(numberOfYears);
String loanAmnt = loan.format(loanAmount);
String total = "Annual Interest Rate:\t" + interestRate + "\nNumber of Years:\t\t" + numOfYears + "\nLoan Amount:\t\t\t" + loanAmnt;
return total;
}
}
My problem is with the getTotalPayment method. It can't access the monthlyPayment variable without me either declaring monthlyPayment as a field, like annualInterestRate, or passing it to the getTotalPayment method. The issue is, getTotalPayment is not allowed to have parameters, and we aren't allowed to have any more fields than the three she instructed us to have, which are the three you'll see declared in the beginning of the code.
So, my question: is there a way to make the variable monthlyPayment accessible to getTotalPayment, without making monthlyPayment a field or giving getTotalPayment a parameter?
You have a spelling error in your getTotalPayment() method.
What your trying to do is call the method getmonthlyPayment() when you should be calling getMonthlyPayment().
Incase you missed the suttle difference in my answer you have a lowercase 'm' when you want an uppercase 'M'.
Im not entirety sure if this is your problem, but its the only syntax error my IDE is telling me.
In your revised code you need upper case M in call to getMonthlyPayment().
When I try to run this bit of code that I wrote:
import java.util.Scanner;
public class F1Calc
{
public static void main(String args[])
{
System.out.println("The coefficient of friction of the " + getSurface() + " surface is " + getCoeff() + ". The mass of the ball was " + getMass() + " and the momentum of the ball was "+ getMomentum() + " Nm. The potential energy contained by the ball at the top of the .121 m high ramp was " + getPotEnergy() + " Joules.");
}
public static String getSurface()
{
Scanner kb = new Scanner(System.in);
System.out.println("What is the surface you are rolling the ball into?");
String surface = kb.nextLine();
kb.close();
return surface;
}
public static double getMass()
{
Scanner kb2 = new Scanner(System.in);
System.out.println("What is the mass of the ball in kilograms?");
double mass = kb2.nextInt();
kb2.close();
return mass;
}
public static double getPotEnergy()
{
double potEnergy = getMass() * .121 * 9.8;
return potEnergy;
}
public static double getMomentum()
{
double doublePE = 2 * getPotEnergy();
double doublePEOverMass = doublePE / getMass();
double velocity = Math.sqrt(doublePEOverMass);
double momentum = velocity * getMass();
return momentum;
}
public static double getCoeff()
{
double coeff = getPotEnergy() / (getMass() * 9.8);
return coeff;
}
}
The following is displayed on the console:
What is the surface you are rolling the ball into?
Tile
What is the mass of the ball in kilograms?
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at F1Calc.getMass(F1Calc.java:20)
at F1Calc.getPotEnergy(F1Calc.java:26)
at F1Calc.getCoeff(F1Calc.java:39)
at F1Calc.main(F1Calc.java:6)
Adding lines so that my post can be submitted. Adding lines so that my post can be submitted. Adding lines so that my post can be submitted. Adding lines so that my post can be submitted.
There is only one underlying InputStream used for Scanner so don't close it - doing so closes it for all future instances of the class making it impossible to read from the source
You do not want to open a new scanner and close it each time. Instead, just create it once.
I also fixed two other bugs in your code.
You were using nextInt() to read a double. This has been replaced with nextDouble().
You are asking the user to input mass multiple times. This has been fixed by caching the value of mass, so it is read from the user only once.
Here is the corrected code.
import java.util.Scanner;
public class F1Calc
{
// Cache the values so we don't have to keep bugging the user
static double mass;
static Scanner kb;
public static void main(String args[])
{
mass = -1;
kb = new Scanner(System.in);
System.out.println("The coefficient of friction of the " + getSurface() + " surface is " + getCoeff() + ". The mass of the ball was " + getMass() + " and the momentum of the ball was "+ getMomentum() + " Nm. The potential energy contained by the ball at the top of the .121 m high ramp was " + getPotEnergy() + " Joules.");
}
public static String getSurface()
{
System.out.println("What is the surface you are rolling the ball into?");
String surface = kb.nextLine();
return surface;
}
public static double getMass()
{
if (mass > 0) return mass;
System.out.println("What is the mass of the ball in kilograms?");
mass = kb.nextDouble();
return mass;
}
public static double getPotEnergy()
{
double potEnergy = getMass() * .121 * 9.8;
return potEnergy;
}
public static double getMomentum()
{
double doublePE = 2 * getPotEnergy();
double doublePEOverMass = doublePE / getMass();
double velocity = Math.sqrt(doublePEOverMass);
double momentum = velocity * getMass();
return momentum;
}
public static double getCoeff()
{
double coeff = getPotEnergy() / (getMass() * 9.8);
return coeff;
}
}
I'm in an intro programming class, in the lab that I'm currently working on we have to have two classes and pull the methods from one class, "Energy" and have them run in "Energy Driver."
I'm having trouble calling the methods (testOne, testTwo, testThree) over into "EnergyDriver"
public class EnergyDriver
{
public static void main(String [] args)
{
System.out.println(mass1 + " kiolograms, " + velocity1 +
"meters per second: Expected 61250," + " Actual " + kineticE1);
System.out.println(mass2 + " kiolograms, " + velocity2 +
"meters per second: Expected 61250," + " Actual " + kineticE2);
System.out.println(mass3 + " kiolograms, " + velocity3 +
"meters per second: Expected 61250," + " Actual " + kineticE3);
}
}
public class Energy
{
public static void main(String [] args)
{
public double testOne;
{
double mass1;
double velocity1;
double holderValue1;
double kineticE1;
mass1 = 25;
velocity1 = 70;
holderValue1 = Math.pow(velocity1, 2.0);
kineticE1 = .5 *holderValue1 * mass1;
}
public double testTwo;
{
double mass2;
double velocity2;
double holderValue2;
double kineticE2;
mass2 = 76.7;
velocity2 = 43;
holderValue2 = Math.pow(velocity2, 2.0);
kineticE2 = .5 *holderValue2 * mass2;
}
public double testThree;
{
double mass3;
double velocity3;
double holderValue3;
double kineticE3;
mass3 = 5;
velocity3 = 21;
holderValue3 = Math.pow(velocity3, 2.0);
kineticE3 = .5 *holderValue3 * mass3;
}
}
You must have only one main method in any one of class. To call a method from another class you can create an object of that class a call their respective method. Another way is by keeping the calling method to be static so you can access that method via Classname.Methodname.
public class EnergyDriver
{
public static void main(String [] args)
{
Energy energy=new Energy();
System.out.println(mass1 + " kiolograms, " + velocity1 +
"meters per second: Expected 61250," + " Actual " + energy.testOne());
System.out.println(mass2 + " kiolograms, " + velocity2 +
"meters per second: Expected 61250," + " Actual " + energy.testTwo());
System.out.println(mass3 + " kiolograms, " + velocity3 +
"meters per second: Expected 61250," + " Actual " + energy.testThree());
}
}
class Energy
{
public double testOne()
{
double mass1;
double velocity1;
double holderValue1;
double kineticE1;
mass1 = 25;
velocity1 = 70;
holderValue1 = Math.pow(velocity1, 2.0);
kineticE1 = .5 *holderValue1 * mass1;
return kineticE1;
}
public double testTwo()
{
double mass2;
double velocity2;
double holderValue2;
double kineticE2;
mass2 = 76.7;
velocity2 = 43;
holderValue2 = Math.pow(velocity2, 2.0);
kineticE2 = .5 *holderValue2 * mass2;
return kineticE2;
}
public double testThree()
{
double mass3;
double velocity3;
double holderValue3;
double kineticE3;
mass3 = 5;
velocity3 = 21;
holderValue3 = Math.pow(velocity3, 2.0);
kineticE3 = .5 *holderValue3 * mass3;
return kineticE3;
}
}
You can get the value of Kinetic Engergy 1,2,3 by using this code.
You can also use the below code which will use only one method to calculate different values by giving different arguments.
public class EngergyDriver
{
public static void main(String [] args)
{
Energy energy=new Energy();
double mass=25;
double velocity=70;
System.out.println(mass+ " kiolograms, "+velocity+"meters per second: Expected 61250," + " Actual " + energy.testOne(mass,velocity));
}
}
class Energy
{
public double testOne(double mass, double velocity)
{
double mass1;
double velocity1;
double holderValue1;
double kineticE1;
mass1 = 25;
velocity1 = 70;
holderValue1 = Math.pow(velocity1, 2.0);
kineticE1 = .5 *holderValue1 * mass1;
return kineticE1;
}
}
Java programs have SINGLE point of entry and that is through the main method.
Therefore in a single project only one class should have the main method and when compiler will look for that when you run it.
Remember that static methods cannot access non static methods hence main is static therefore it can not access testone two nor three UNLESS you create and object of that type. Meaning in the main method you can have Energy e = new Energy() then access those methods that were not declared with keyword static like e.testone() .
However take note that non static methods can access static methods through Classname.Method name because keyword static entails that only a single copy of that method/variable exists therefore we do not need an object to access it since only one copy exists.
I recommend watching the Java videos from Lynda.com or reading the books Java Head First and Java How To Program (Deitel,Deitel) to give you a boost on your Java knowledge they come with alot of exercises to enhance your knowledge.
Also there are plenty of other questions like this on SO search for them