Java: method not returning to main - java

In Java for some reason the averageSpeed method is not returning a double value or any value. It seems that the method never exits back to the main method for some reason. I do not understand why this happens.
The values I input are accordingly 0, 30, 14, 15, 14, 45. I expect the double 60.0 to be returned.
import java.util.Scanner;
/**
* Auto Generated Java Class.
*/
public class CarSpeed {
/**
* Computes a car's average speed over the legnth of a trip.
*
* #param milesStart odometer reading at the start of the trip
* #param milesEnd odometer reading at the end of the trip
* #param hrsStart hours on the (24 hour) clock at the start
* #param minsStart minutes on the clock at the start
* #param hrsEnd hours on the (24 hour) clock at the end
* #param minsEnd minutes on the clock at the end
* #return the average speed (in miles per hour)
*/
public static double averageSpeed(double milesStart, double milesEnd,
double hrsStart, double minsStart, double hrsEnd, double minsEnd) {
double distanceTraveled;
double minutes;
double hours;
double sixty;
double minuteHours; //minutes converted into hours
double time;
double averageSpeed;
distanceTraveled = milesEnd - milesStart;
minutes = minsEnd - minsStart;
sixty = 60;
minuteHours = minutes/sixty;
hours = hrsEnd - hrsStart;
time = minuteHours + hours;
averageSpeed = distanceTraveled/time;
return averageSpeed;
}
/**
* #param args
*/
public static void main(String[] args) {
double milesStart;
double milesEnd;
double hrsStart;
double minsStart;
double hrsEnd;
double minsEnd;
Scanner input = new Scanner(System.in);
System.out.print("What is the odometer reading at the start of the trip?");
milesStart = input.nextDouble();
System.out.print("What is the odometer reading at the end of the trip?");
milesEnd = input.nextDouble();
System.out.print("What is the hours on the 24 hr clock at the start?");
hrsStart = input.nextDouble();
System.out.print("What is the minutes on the clock at the start?");
minsStart = input.nextDouble();
System.out.print("What is the hours on the 24 hr clock at the end?");
hrsEnd = input.nextDouble();
System.out.print("What is the minutes on the clock at the end?");
minsEnd = input.nextDouble();
averageSpeed(milesStart, milesEnd, hrsStart, minsStart, hrsEnd, minsEnd);
}
}

You dont see any value, because you didnt even store it. It should work good, but you should edit last line from averageSpeed(milesStart, milesEnd, hrsStart, minsStart, hrsEnd, minsEnd); to System.out.println(averageSpeed(milesStart, milesEnd, hrsStart, minsStart, hrsEnd, minsEnd));. Then you will be able to display returned variable.

If the method has a return value, you must create an Object to save it.
Double avgSpeed = averageSpeed(milesStart, milesEnd, hrsStart, minsStart, hrsEnd, minsEnd);
System.out.println("Average Speed is " + avgSpeed);

Remember that returning a value does not mean printing it. You can assign the returned double to some variable like:
double result = yourFunction(arg1, arg2, arg3, arg4, arg5, arg6);
And then you can print it out to the console:
System.out.println(result);
The second option is printing it out straight away from the function:
System.out.println(yourFunction(arg1, arg2, arg3, arg4, arg5, arg6));

Related

I wrote a mortgage calculator code but when i debugged it i got an exception [duplicate]

This question already has answers here:
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed 3 years ago.
import java.text.NumberFormat;
public class Mortgage {
public static void main(String[] args) {
int p = 1000000;
NumberFormat percent = NumberFormat.getPercentInstance();
double r = Double.parseDouble(percent.format(3.92*12));
int t = (int)(r);
double n;
n = Math.pow(30,12);
int f = (int) Math.floor(n);
int a =(1+t)^f;
int b = (a-1);
int c = (t*a)/b;
int m = p*c;
NumberFormat currency = NumberFormat.getCurrencyInstance();
String result = currency.format(m);
System.out.println(result);
}
}
I have tried to changed r to int but I still got exception. What am I not writing correctly?
You use NumberFormat.getPercentInstance() to format your number. This adds a % symbol and other number formatting (depending on your default locale). Then the Double.parseDouble(...) call fails because the number is not a pure double number.
There is no need to format and parse the number, you can just assign it directly to the double variable as it is a constant anyways.
I see several problems.
double n;
n = Math.pow(30,12);
int f = (int) Math.floor(n);
30 to the 12th power. That does not make sense for a 30 year mortgage Did you mean 30*12 for 360 pay periods. Or possibly Math.pow(30,1+montlyRate) where monthlyRate = (AR/100)/12 and AR = annual rate).
int a =(1+t)^f;
The operator ^ is not power but an exclusive OR. You probably didn't want that either.
I recommend you check out this Wiki entry on computing Mortage Payments
Here is one way to do calculate it and then display it per month.
double in = 5.5; // annual percentage rate
double mo_rate = (in / 100) / 12.; // monthly rate
double PV = 400_000.; // present value (cost of the house).
double f = Math.pow(1 + mo_rate, 360); // factor resulting from the linear
// expansion
double payment = mo_rate * PV * f / (f - 1); // Monthly payment including
// interest and
// principal
System.out.printf("Monthly payment is %7.2f%n", payment);
Note: different banks and/or countries may do it differently.
The answer is in the exception java.lang.NumberFormatException: For input string: "4,704%"
percent.format(3.92*12) returns the String : 4 704 % and this can't be parsed to double, because of the space and the % symbol, you just need to multiply it by 100 to consider it as a percentage
double r = 3.92 * 12 * 100;
As you're using only ints you fall into the int division problem and you'll get a 0 at the end, so you may use at leat one double ot cast one durint the division
int a = (1 + t) ^ f;
double b = (a - 1);
double c = (t * a) / b;
double m = p * c;
// OR
int a = (1 + t) ^ f;
int b = (a - 1);
double c = (t * a) / (double) b;
double m = p * c;
Also ^ is thr XOR symbol, to use power computation :
double a = Math.pow(1+t, f);
For the result, it depends on r:
double r = 3.92 * 12 * 100; gives -10 308,38 €
double r = 3.92 * 12; gives 999 998,95 €
And use names that explain what the variable is, as much as possible

Is there a way to represent variables as int instead of double to calculate correct percentage? [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 6 years ago.
I am doing exercise 2.3 on page 23 of Think Java (http://www.greenteapress.com/thinkapjava/thinkapjava.pdf).
The program converts an arbitrary time stored in variables to seconds, then calculates the amount of seconds remaining in the day, then how much of the day has elapsed in percentage.
Here's the working program:
public class Time {
public static void main(String[] args) {
double hour = 21.0; //Represents 9 PM
double minute = 5.0; //Represents 9:05 PM
double second = 33.0; //Represents 9:05:33 PM
final double SEC_IN_MIN = 60.0; //Made final because the amount of seconds in a minute does not change
final double SEC_IN_HOUR = 3600.0; //Made final for the same reason above.
final double SEC_SINCE_MN = (SEC_IN_HOUR * hour) + (SEC_IN_MIN * minute) + second; //Calculates the seconds since midnight, or 00:00
final double SEC_IN_DAY = 24.0 * SEC_IN_HOUR; //Calculates the amount of seconds in a day; 24 stands for the hours in a day
System.out.printf("The number of seconds since midnight is: %.0f\n", SEC_SINCE_MN);
System.out.printf("The number of seconds remaining in the day is: %.0f\n", SEC_IN_DAY - SEC_SINCE_MN);
System.out.printf("The percentage of the day that has passed is: %.0f%%", (100 * SEC_SINCE_MN) / SEC_IN_DAY); // Escape percent sign is %% 100 * to remove decimal value
}
}
I know there is a better way with more advanced code but this is what the assignment required based on what we have learned so far. However, I am not sure double is the best way to represent the variables as I have to use a format specifier to trim the decimal. I asked my professor about it and he said I could change all the variables to int and change the computation in the last print statement to:
System.out.printf("The percentage of the day that has passed is: %d%%", (100 * SEC_SINCE_MN) * 1.0 / SEC_IN_DAY);
This does not work because I get a d != java.lang.Double error for the last print statement. If I change the 1.0 to 1, I get no errors put the last output is incorrect.
It says 87% instead of 88% which is the correct output because the decimal value for the last print statement output is 0.08788.
I think it's my computation that needs to be changed for it to work with int.
Any ideas on how to edit the program for int instead of double?
EDIT 1: Code that doesn't work as per my professor's suggestions (returns java.lang.double error for last print statement)
public class Time {
public static void main(String[] args) {
int hour = 21; //Represents 9 PM
int minute = 5; //Represents 9:05 PM
int second = 33; //Represents 9:05:33 PM
final int SEC_IN_MIN = 60; //Made final because the amount of seconds in a minute does not change
final int SEC_IN_HOUR = 3600; //Made final for the same reason above.
final int SEC_SINCE_MN = (SEC_IN_HOUR * hour) + (SEC_IN_MIN * minute) + second; //Calculates the seconds since midnight, or 00:00
final int SEC_IN_DAY = 24 * SEC_IN_HOUR; //Calculates the amount of seconds in a day; 24 stands for the hours in a day
System.out.printf("The number of seconds since midnight is: %d\n", SEC_SINCE_MN);
System.out.printf("The number of seconds remaining in the day is: %d\n", SEC_IN_DAY - SEC_SINCE_MN);
System.out.printf("The percentage of the day that has passed is: %d%%", (100 * SEC_SINCE_MN) * 1.0 / SEC_IN_DAY); // Escape percent sign is %%. 100 * to remove decimal value
}
}
EDIT 2: Code that works but doesn't give the correct output of 88% for the last print statement
public class Time {
public static void main(String[] args) {
int hour = 21; //Represents 9 PM
int minute = 5; //Represents 9:05 PM
int second = 33; //Represents 9:05:33 PM
final int SEC_IN_MIN = 60; //Made final because the amount of seconds in a minute does not change
final int SEC_IN_HOUR = 3600; //Made final for the same reason above.
final int SEC_SINCE_MN = (SEC_IN_HOUR * hour) + (SEC_IN_MIN * minute) + second; //Calculates the seconds since midnight, or 00:00
final int SEC_IN_DAY = 24 * SEC_IN_HOUR; //Calculates the amount of seconds in a day; 24 stands for the hours in a day
System.out.printf("The number of seconds since midnight is: %d\n", SEC_SINCE_MN);
System.out.printf("The number of seconds remaining in the day is: %d\n", SEC_IN_DAY - SEC_SINCE_MN);
System.out.printf("The percentage of the day that has passed is: %d%%", (100 * SEC_SINCE_MN) / SEC_IN_DAY); // Escape percent sign is %%. 100 * to remove decimal value
}
}
EDIT 3: This is not a dupe question. My question was how to convert the variables to int from doubles, so the percentage was calculated correctly in the last statement. I was not asking about rounding although it did play a part in the question/answer.
The int throws what's after the period. You may want to duplicate in 10 more. Get the first numeral to check if it greater than 5 add one to your percent.
Sorry for not writing code.
I'm on iOS now and my java rusty...
Good luck
(100 * SEC_SINCE_MN) / SEC_IN_DAY
is multiplying the integer SEC_SINCE_MN by the integer 100, and then divides it by the integer SEC_IN_DAY. So that's an integer division. It just truncates the decimal part of the result.
What you want is to compute the accurate percentage, with the decimals, and then round the result. So you need a floating point division:
(100.0 * SEC_SINCE_MN) / SEC_IN_DAY
That will produce a double value (87.88541666666667), that you then need to round:
Math.round((100.0 * SEC_SINCE_MN) / SEC_IN_DAY)

Calculate and Display the Percentage of Time Passed

I'm going through ThinkJava Version 6.1.0 (latest) and in Chapter 2 Exercise 2.3, I'm stuck on #5 which asks "Calculate and display the percentage of the day that has passed. You might run into problems when computing percentages with integers, so consider using floating-point."
I've attempted to get the percentage, but I'm not getting the right result.
I've completed the first 4 questions. Here is what I have so far:
public class Date {
public static void main(String[] args) {
int hour = 13, minute = 58, second = 45;
double percentage;
double secondsSinceMidnight = second + (minute * 60) + (hour * 3600);
double secondsRemainingInDay = (60-second) + ((60-1-minute)*60) + (24-1-hour)*3600;
percentage = (secondsSinceMidnight * 100) / 60;
System.out.println("Number of seconds since midnight:");
System.out.println(secondsSinceMidnight);
System.out.println("Number of seconds remaining in the day:");
System.out.println(secondsRemainingInDay);
System.out.println("Percentage of the day past:");
System.out.println(percentage + "%");
}
}
Thank you for your help and support!
Please check the formula for calculating the percentage of the day already past.
percentage = (secondsSinceMidnight * 100) / 60;
Does not seem right to me. It should be something like
percentage = 100 * secondsSinceMidnight / totalSecondsInDay;
totalSecondsInDay can be the sum of secondsRemainingInDay and secondsSinceMidnight
i think your code have problems with type-casting
in line 3 exchange int with double:
double hour = 13, minute = 58, second = 45;
or there is problem with constant numbers , write numbers in this way : 60.0 instead of 60
Here's an example with a hardcoded time. It's in military time obviously so keep that in mind.
public class Time
{
public static void main(String[] args) {
int startHour = 12; //when you start editing program
int startMinute = 00;
int startSecond = 00;
System.out.print("Number of seconds since midnight: ");
startMinute = (startHour * 60 + startMinute );
startSecond = (startMinute * 60 + startSecond);
System.out.print(startSecond);
System.out.println(" seconds");
int secondInADay = 86400; //number of seconds in a day
System.out.print ("Seconds remaining in the day: ");
System.out.println (secondInADay - startSecond);
System.out.print("Percent of the day that has passed: ");
double startSeconds = 43200; //number of seconds that have passed in a day at start of editing program
System.out.println(startSeconds * 100 / 86400);
int endHour = 16; //time when finished editing program
int endMinute = 00;
int endSecond = 00;
System.out.print ("Difference = "); //difference in time from start to finish
endMinute = (endHour * 60 + endMinute );
endSecond = (endMinute * 60 + endSecond);
System.out.print (endSecond - startSecond);
System.out.print (" seconds");
}
}

Java Currency Converter (How to convert int to Double + Many other issues)

I'm struggling with finding the remainders when converting the currency and then dividing it into dollar amounts. Also, creating a minimum amount of currency to be converted is causing me an issue. I understand alot of my code is a mess but this is my first Java project. Any help would be much appreciated.
/* Currency Conversion
*/
import java.util.Scanner;//to get keyboard input from user
public class Currency {
/**
* Converts from a foreign currency to US Dollars. Takes a
* deduction for the transaction fee. Displays how many of
* each bill and coin denomination the user receives.
*
* #param args no parameters expected
*/
public static void main(String[] args)
{
final double SEK_CONVERSION_RATE = .14;
/*
* You'll need a variable or constant for the transaction fee.
* (3% is fairly typical.) You'll also need a variable or
* constant for the minimum transaction fee.
*/
double transactionFee = .03;
final double MIN_TRANSACTION_FEE = 10.00;
/*
* You're going to need a variable for the amount of that
* currency the user wants to convert.
*/
//Before you can ask the user for input, you need a Scanner so you can read
//that input:
Scanner keyboard = new Scanner(System.in);
/*
* Now you're ready to interact with the user. You'll want
* to greet them and let them know what currency they can convert
* and what the rate of exchange is.
*/
System.out.print("Hello there, welcome to your one and only stop for Swedish Krona conversions. The exchange rate currently sits at .14" );
/*
* You should also let them know about the transaction fee.
*/
System.out.println(" The minimum transaction fee is $10.00 USD.");
/*
* Now you're ready to prompt the user for how much money they
* want to convert.
*/
System.out.println("How many Swedish Krona would you like to convert to US Dollar?");
double userCurrencyInput = keyboard.nextDouble();
/*
* And then use the Scanner to read in that input and initialize your
* variable for currency:
*/
double calculatedCurrInput = (userCurrencyInput*SEK_CONVERSION_RATE);
/* setting up casting to use later in program */
int calculatedCurrInputInt = (int) (calculatedCurrInput);
/*
* You've received an amount in a foreign currency, but you're going
* to need the amount in dollars. Furthermore, you're going to need
* to know the number of 20's, 10's,5's, 1's, quarters, dimes, nickels
* and pennies. And you're going to need to know the transaction fee.
* These should all be stored in variables.
*/
double totalTransaction = (userCurrencyInput*transactionFee + calculatedCurrInput);
int totalTransactionInt = (int) (totalTransaction);
/*Need to define the remainder correct to make change*/
System.out.println("The conversion is " + calculatedCurrInput);
int twentyDollar = 20;
int twentyDollarBills = calculatedCurrInputInt/twentyDollar;
int remainderOfTwenty = calculatedCurrInputInt%twentyDollar;
int tenDollar = 10;
int tenDollarBills = remainderOfTwenty/tenDollar;
int remainderOfTen = remainderOfTwenty%tenDollar;
int fiveDollar = 5;
int fiveDollarBills = remainderOfTen/fiveDollar;
int remainderOfFive = remainderOfTen%fiveDollar;
int oneDollar = 1;
int oneDollarBills = remainderOfFive/oneDollar;
int remainderOfOnes = remainderOfFive%oneDollar;
double remainderOfOnesDBL = (double) remainderOfOnes;
double quarter = .25;
double numberOfQuarters = remainderOfOnesDBL/quarter;
double remainderOfQuarters = remainderOfOnesDBL%quarter;
double dimes = .10;
double numberOfDimes = remainderOfQuarters/dimes;
double remainderOfDimes = remainderOfQuarters%dimes;
double nickels = .05;
double numberOfNickels = remainderOfDimes/nickels;
double remainderOfNickels = remainderOfDimes%nickels;
double pennies = .01;
double numberOfPennies = remainderOfNickels/pennies;
/*
* Now you're ready to calculate the amount in USD.
*/
/*
* Determine what the transaction fee would be, based on the
* percentage.
*/
double totalTransactionFee = (userCurrencyInput*transactionFee);
System.out.println("The transcation fee for your currency exchange would be $" + totalTransactionFee + " US.");
/*
* If the transaction fee is less than the minimum transaction
* fee, you'll need to charge the minimum transaction fee.
* (Hint, the Math class has min and max methods that receive
* two numbers and return either the smaller or larger of those
* two numbers.)
*/
/*
* You'll need to deduct the transaction fee from the total.
*/
/*
* Calculate the number of $20's they'll receive
*/
/*
* How much is left?
*/
/*
* Next do the same for $10's, $5's, etc.
*/
/*
* Finally, let the user know how many dollars their foreign currency
* converted to, what was deducted for the transaction fee, and how
* many of each denomination they are receiving.
*/
System.out.println("The amount of 20's is " +twentyDollarBills);
System.out.println("The amount of 10's is " +tenDollarBills);
System.out.println("The amount of 5's is " +fiveDollarBills);
System.out.println("The amount of 1's is " +oneDollarBills);
System.out.println("The amount of quarters is " +numberOfQuarters);
System.out.println("The amount of dimes is " +numberOfDimes);
System.out.println("The amount of nickels is " +numberOfNickels);
System.out.println("The amount of pennies is " +numberOfPennies);
}//end main
}//end Currency
Firstly, you shouldn't be converting from doubles to ints, as you will lose the amount after the decimal point. e.g.
double num = 1.9;
int number = (int) num;
System.out.println(number);
will print
1
Also, if you do
System.out.println(num % 1);
you get
0.8999999999999999 // not quite 0.9, which is what you were expecting
As #Laf pointed out, use BigDecimal instead.
BigDecimal SEK_CONVERSION_RATE = new BigDecimal(".14");
String userInput = keyboard.nextLine();
// Better precision constructing from a String
BigDecimal userCurrencyInput = new BigDecimal(userInput);
BigDecimal calculatedCurrInput = userCurrencyInput.multiply(SEK_CONVERSTION_RATE);
Hopefully you can work out the rest from there.
Hint: BigDecimal has a method divideAndRemainder() which returns a BigDecimal[], where the first part is the quotient, and the second part is the remainder.
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#divideAndRemainder%28java.math.BigDecimal%29

determine the periodic loan payment

am not getting this program to display my instalments correctly can I please get some help thanks......
package Loops;
import java.util.Scanner;
/**
*
*
*/
public class program {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//variabled decleared
double rate;
double payment;
//input
System.out.print("Enter Loan Amount:");
double principal = input.nextDouble();
System.out.print("Enter Annual Interest:");
double interest = input.nextDouble();
System.out.print("Total payments per year:");//12=monthly,4= quartely,2=semi-annually and 1=annually
double period = input.nextDouble();
System.out.print("Enter Loan Length :");
int length = input.nextInt();
//proces
double n = period * length;
rate = interest / 100;
double monthly_rate = rate / period;
payment = principal * (principal * (monthly_rate * Math.pow((1 + monthly_rate), n)));
System.out.printf("Your Monthly sum is %.2f", payment);
}
}
principal = 50000; //Redacted. Eating my words.
period = 4;
length = 4;
n = 16;
rate = 0.085;
monthly_rate = 0.085 / 16 = 0.0053125;
payment = 50000 * 50000 * 0.0053125 * (1 + 0.0053125) ^ 16;
= 2.5x10^9 * 0.0053125 * 1.088;
= Something remainingly massive
Basically... your formula is wrong. Wouldn't you need to divide by the power quotient? Where is your source on that formula?
payment = principal * (rate + (rate / ( Math.pow(1 + rate, n) - 1) ) );
Source
Example:
payment = 50000*(0.085+(0.085/(1.085^16-1)))
= 5830.68
Try this for your formula:
//this is how much a monthly payment is
payment = (rate + (rate / ((Math.pow(1 + rate), n) -1)) * principal
This is based off one of the first google results for the formula. Please post the results and expected answer if it is wrong.
I'm pretty sure your formula is just off, as you stated above that there should be a denominator in the equation.
You can use r* Math.pow ((1+r),n) to calculate the numerator and part of the denominator

Categories

Resources