Return in the method overloading - java

I'm new to Java and I'm learning it myself. I met a trouble when I try the method overloading. This is the code
public static void main(String[] args) {
calculateScore();
calculateScore(500);
calculateScore("Duy", 600);
calcFeetAndInchesToCentimetres(100, 3.5);
calcFeetAndInchesToCentimetres(100*12 + 3.5);
}
public static double calcFeetAndInchesToCentimetres(double feet, double inches) {
if (feet >= 0 && inches >= 0 && inches <= 12) {
double footToInches = feet * 12;
double centimetres = (inches + footToInches) * 2.54;
System.out.println("The value in centimetres is " + centimetres + " cm.");
return centimetres;
} else {
return -1;
}
}
public static double calcFeetAndInchesToCentimetres(double inches) {
if (inches >= 0){
double inchesToFeet = inches / 12;
double inchesRemain = inches - (inchesToFeet * 12);
calcFeetAndInchesToCentimetres(inchesToFeet, inchesRemain);
return 0;
} else {
return -1;
}
My problem is when I take the return 0 from the second method, the debugger says "missing return statement". Then I tried to put return calcFeetAndInchesToCentimetres(inches);, it works but the program runs for about many thousands times.
Then I put return 0 and everything is OK. But I don't understand why I can't put the return calcFeetAndInchesToCentimetres(inches); and why do I need a return statement when the method above (with 2 parameters) had it alredy. And if I want to have the value of centimetres converted when I execute the second method (with "inches" parameter only) what do I have to do?
One other thing I've realized that in this blockcode
double inchesToFeet = inches / 12;
double inchesRemain = inches - (inchesToFeet * 12);
calcFeetAndInchesToCentimetres(inchesToFeet, inchesRemain);
the inchesRemain will be 0? But the method works very well. When I change inchesToFeet = inches % 12, it just not shows anything. Why?

It should just be:
public static double calcFeetAndInchesToCentimetres(double inches) {
if (inches >= 0){
double inchesToFeet = inches / 12;
double inchesRemain = inches - (inchesToFeet * 12);
return calcFeetAndInchesToCentimetres(inchesToFeet, inchesRemain);
} else {
return -1;
}
}
You said you've tried return calcFeetAndInchesToCentimetres(inches); but that's just calling your method recursively and it recurses forever as there is no stopping condition.

With method overloading, you have two different methods.
calcFeetAndInchesToCentimetres that takes a single argument
calcFeetAndInchesToCentimetres that takes two arguments
Now when you call calcFeetAndInchesToCentimetres(inches); you are calling the one that takes a single argument. If you call that from inside itself, it will continue calling itself infinite times. This is the error you are seeing.
If you replace that with return calcFeetAndInchesToCentimetres(inchesToFeet, inchesRemain); that will call the other method - the one that takes two arguments. That's what you actually want to do.
Fixed version:
public static double calcFeetAndInchesToCentimetres(double inches) {
if (inches >= 0){
double inchesToFeet = inches / 12;
double inchesRemain = inches - (inchesToFeet * 12);
return calcFeetAndInchesToCentimetres(inchesToFeet, inchesRemain);
} else {
return -1;
}
}

public static void main(String[] args) {
calculateScore();
calculateScore(500);
calculateScore("Duy", 600);
calcFeetAndInchesToCentimetres(100, 3.5);
calcFeetAndInchesToCentimetres(100*12 + 3.5);
}
public static double calcFeetAndInchesToCentimetres(double feet, double inches) {
if (feet >= 0 && inches >= 0 && inches <= 12) {
double footToInches = feet * 12;
double centimetres = (inches + footToInches) * 2.54;
System.out.println("The value in centimetres is " + centimetres + " cm.");
return centimetres;
} else {
return -1;
}
}
public static double calcFeetAndInchesToCentimetres(double inches) {
if (inches >= 0){
double inchesToFeet = inches / 12;
double inchesRemain = inches - (inchesToFeet * 12);
calcFeetAndInchesToCentimetres(inchesToFeet, inchesRemain);
return 0; //Here
} else {
return -1;
}
If you remove return 0 it is showing missing return statement because you are in a if-else loop.
Lets say your input inches is less than 0 then it will go the else part and return the -1.. but if the inches inputed are more than 0 then it will go to the if condition and when it will reach the end of the if statement then there would be nothing to return so for a if-else condition both if and else should return something.
Other way to go around this is make a local variable out of if-else condition and return if after the else part is done.. In this way weather it goes in if or else part of the code both times there would be some value for that local variable to be returned..
Now for second part of your question:
your code will look like
line 1 public static double calcFeetAndInchesToCentimetres(double inches) {
line 2 if (inches >= 0){
line 3 double inchesToFeet = inches / 12;
line 4 double inchesRemain = inches - (inchesToFeet * 12);
line 5 calcFeetAndInchesToCentimetres(inchesToFeet, inchesRemain);
line 6 return calcFeetAndInchesToCentimetres(inches);
} else {
return -1;
}
So in this case you are calling the same method itself again and again..
You start from line 1 go till line 6 then you call the same method and the execution starts again and line 1 will be executed till line 6 and again line 1 over and over again until all memory is lost and a stackoverflow occours..
Best practiced code can look like this:
public static double calcFeetAndInchesToCentimetres(double feet, double inches) {
double centimetres = 0.0;
if (feet >= 0 && inches >= 0 && inches <= 12) {
double footToInches = feet * 12;
centimetres = (inches + footToInches) * 2.54;
System.out.println("The value in centimetres is " + centimetres + " cm.");
} else {
centimetres = -1;
}
return centimetres;
}
public static double calcFeetAndInchesToCentimetres(double inches) {
double centimeters = 0;
if (inches >= 0) {
double inchesToFeet = inches / 12;
double inchesRemain = inches - (inchesToFeet * 12);
centimeters = calcFeetAndInchesToCentimetres(inchesToFeet, inchesRemain);
} else {
centimeters = -1;
}
return centimeters; //Here
}

Related

(Java)Calculating the number of years to get to a specific balance

Here's the prompt:
There is a bank account that earns 5 percent interest per year. The initial account balance is $10000. Given a target balance (for example, $20000), return the number of years that it takes for the account balance to reach the target balance. The number of years should be an integer.
Here's my code:
public int getNumberOfYears(double targetBalance){
int years = 1;
for (double balance = 10000.0; balance <= targetBalance; years++) {
double multiplier = Math.pow(1.05, years);
balance *= multiplier;
}
return years;
}
When this runs, [multiplier] increases by the following pattern:
1.05^1 --> (1.05^1)^2 --> ((1.05^1)^2)^3 --> etc.
How do I fix my code so that [multiplier] increases by the following pattern:
1.05^1 --> 1.05^2 --> 1.05^3 --> etc?
When you do balance * Math.pow(1.05, years) that means you directly apply the increase for years, you want to go year by year, so just use the 1.05.
Also for that kind of problem, a while loop is prefered
public static int getNumberOfYears(double targetBalance) {
int years = 1;
double balance = 10000;
while (balance <= targetBalance) {
balance *= 1.05;
years++;
}
return years;
}
You don't need to increase the multiplier - every year carries the same interest, and you just need to keep multiplying by the same interest rate every year:
public int getNumberOfYears(double targetBalance) {
int years = 1;
double multiplier = 1.05;
for (double balance = 10000.0; balance < targetBalance; years++) {
balance *= multiplier;
}
return years;
}
EDIT:
As a side note, this can be solved without a loop, by extracting a log of both sides of the equation:
10000 * 1.05year = target
1.05year = target / 10000
log(1.05year) = log(target / 10000)
year * log(1.05) = log(target / 10000)
year = log(target / 10000) / log(1.05)
Or, in java:
public int getNumberOfYears(double targetBalance) {
double years = Math.log(targetBalance / 10000) / Math.log(1.05);
return (int) Math.ceil(year);
}
The following code will give you the answer in years. You can test it in excel by adding some formulas, the result is correct:
public class practice {
public static void main(String[] args) {
double interestRate = 0.05;
double initialAmount = 10000.00;
double targetValue = 20000.00;
int numYears = 0;
while(targetValue > initialAmount) {
initialAmount += (initialAmount * interestRate);
numYears++;
}
System.out.println("Year to hit target: " + numYears);
System.out.println("Final Amount: " + initialAmount);
}
}
You can use a while loop instead of for.
public int getNumberOfYears(double targetBalance){
int years = 1;
double balance = 10000.0;
while (1) {
if ( balance * 1.05 * years >= targetBalance) {
break;
}
else {
years++;
continue;
}
}
return years;
}
But you should consider on what happens to the interest earned on a year, is it being added to the current balance or added separately. If it is being added to the starting balance of the account consider following code.
public int getNumberOfYears(double targetBalance){
int years = 0;
double balance = 10000.0;
while (balance < targetBalance ) {
balance *= 1.05;
years ++;
}
return years;
}

Why do I get number 320.04 printed to the console in the below code?

I read the below code a lot of times and I cannot figure out why I get the 320.04 on the console. Can someone kindly help me figure out?
package com.heshanshivantha;
public class Main {
public static void main(String[] args) {
calcFeetAndInchesToCentimeters(126);
}
public static double calcFeetAndInchesToCentimeters(double feet, double inches) {
if (feet >= 0 && inches >= 0 && inches <= 12) {
System.out.println(feet * 12 * 2.54 + inches * 2.54);
double centimeters = feet * 12 * 2.54 + inches * 2.54;
System.out.println(feet + " feet " + inches + " inches = " + centimeters + " cm");
return centimeters;
} return -1;
}
public static double calcFeetAndInchesToCentimeters(double inches) {
if (inches >= 0) {
int feet =(int) (inches / 12);
int remainingInches =(int) (inches % 12);
System.out.println(inches + " inches is equal to " + feet + " feet and " + remainingInches + " inches");
return calcFeetAndInchesToCentimeters(feet, remainingInches);
} return -1;
}
}
126.0 inches is equal to 10 feet and 6 inches
320.04
10.0 feet 6.0 inches = 320.04 cm
Process finished with exit code 0
That's because of the first line after the if condition.
Remove System.out.println(feet * 12 * 2.54 + inches * 2.54); and you are done.

BodyMassIndex calculator error (NaN)

I am getting a NaN error when I compile this, i can't figure out what I am doing wrong? I tried moving the variables around to see if I could get them working but nothing. Notice the variable I put of type double i used for bmi after inches = keyboard.nextInt(); I think its a divide by zero error but i dont know what i am dividing by zero.
import java.util.Scanner;
public class BodyMassIndex {
public static void main(String[] args) {
// TODO Auto-generated method stub
int pounds =0;
int feet = 0;
int inches = 0;
double heightMeters = ((feet * 12) + inches) * .0254;
double mass = pounds / 2.2;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your weight in pounds");
pounds = keyboard.nextInt();
System.out.println("Enter how many feet you are");
feet = keyboard.nextInt();
System.out.println("Enter how many inches after feet");
inches = keyboard.nextInt();
double bmi = mass / (heightMeters * heightMeters);
System.out.println(mass);
System.out.println(bmi);
if(bmi < 18.5){
System.out.println("Underweight");
}
else if ((bmi >= 18.5) && (bmi < 25)){
System.out.println("Normal weight");
}
else if ((bmi >= 25) && (bmi < 30))
System.out.println("Above weight");
else
System.out.println("Obese");
}
}
It's important to understand the dynamic nature of your variables, such that when you type
double heightMeters = ((feet * 12) + inches) * .0254;
This assignment is immediately evaluated using the current values of feet and inches (which are 0 at that moment), before any of the keyboard entry is performed. To perform these calculations with the values entered by the keyboard, these calculations need to be performed and their results assigned to their corresponding variables after the keyboard entry is done, when the current values of pounds, feet and inches are what you just entered. Because heightMeters is still zero from its initialization and hasn't been changed since, you're getting a divide by zero.
You're getting the exception because the value of heightMeters is 0 here:
double bmi = mass / (heightMeters * heightMeters);
The only time that heightMeters is calculated, the result of it is 0:
double heightMeters = ((feet * 12) + inches) * .0254;
It looks like you want to use this calculation, so I'd split it into a separate function:
public static double getHeightInMeters(int feet, int inches)
{
return 0.0254 * ((feet * 12) + inches);
}
Then you can call it later:
double heightMeters = this.getHeightInMeters(feet, inches);
double bmi = mass / (heightMeters * heightMeters);

Java - Odd error message when converting double to BigDecimal

In a program, a double is being converted to BigDecimal. This returns a very strange error message.
public static double riemannFuncForm(double s) {
double term = Math.pow(2, s)*Math.pow(Math.PI, s-1)*
(Math.sin((Math.PI*s)/2))*gamma(1-s);
if(s == 1.0 || (s <= -1 && s % 2 == 0) )
return 0;
else if (s >= 0 && s < 2)
return getSimpsonSum(s);
else if (s > -1 && s < 0)
return term*getSimpsonSum(1-s);
else
return term*standardZeta(1-s);
}
BigDecimal val = BigDecimal.valueOf(riemannFuncForm(s));
System.out.println("Value for the Zeta Function = "
+ val.toEngineeringString());
This returns
Exception in thread "main" java.lang.NumberFormatException
What is causing this error message? Does BigDecimal.valueOf(double) not work correctly since this is referenced through another method?
Full program
/**************************************************************************
**
** Euler-Riemann Zeta Function
**
**************************************************************************
** XXXXXXXXXX
** 06/20/2015
**
** This program computes the value for Zeta(s) using the standard form
** of Zeta(s), the Riemann functional equation, and the Cauchy-Schlomilch
** transformation. A recursive method named riemannFuncForm has been created
** to handle computations of Zeta(s) for s < 2. Simpson's method is
** used to approximate the definite integral calculated by the
** Cauchy-Schlomilch transformation.
**************************************************************************/
import java.util.Scanner;
import java.math.*;
public class ZetaMain {
// Main method
public static void main(String[] args) {
ZetaMain();
}
// Asks the user to input a value for s.
public static void ZetaMain() {
double s = 0;
double start, stop, totalTime;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the value of s inside the Riemann Zeta " +
"Function: ");
try {
s = scan.nextDouble();
}
catch (Exception e) {
System.out.println("You must enter a positive integer greater " +
"than 1.");
}
start = System.currentTimeMillis();
if (s == 1)
System.out.println("The zeta function is undefined for Re(s) " +
"= 1.");
else if (s < 2) {
BigDecimal val = BigDecimal.valueOf(riemannFuncForm(s));
System.out.println("Value for the Zeta Function = "
+ val.toEngineeringString());
}
else
System.out.println("Value for the Zeta Function = "
+ BigDecimal.valueOf(getStandardSum(s)).toString());
stop = System.currentTimeMillis();
totalTime = (double) (stop-start) / 1000.0;
System.out.println("Total time taken is " + totalTime + " seconds.");
}
// Standard form of the Zeta function.
public static double standardZeta(double s) {
int n = 1;
double currentSum = 0;
double relativeError = 1;
double error = 0.000001;
double remainder;
while (relativeError > error) {
currentSum = Math.pow(n, -s) + currentSum;
remainder = 1 / ((s-1)* Math.pow(n, (s-1)));
relativeError = remainder / currentSum;
n++;
}
System.out.println("The number of terms summed was " + n + ".");
return currentSum;
}
// Returns the value calculated by the Standard form of the Zeta function.
public static double getStandardSum(double s){
return standardZeta(s);
}
// Approximation of the Gamma function through the Lanczos Approximation.
public static double gamma(double s){
double[] p = {0.99999999999980993, 676.5203681218851,
-1259.1392167224028, 771.32342877765313,
-176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6,
1.5056327351493116e-7};
int g = 7;
// Implements Euler's Reflection Formula.
if(s < 0.5) return Math.PI / (Math.sin(Math.PI * s)
*gamma(1-s));
s -= 1;
double a = p[0];
double t = s + g + 0.5;
for(int i = 1; i < p.length; i++){
a += p[i] / (s+i);
}
return Math.sqrt(2*Math.PI)*Math.pow(t, s+0.5)
*Math.exp(-t)*a;
}
/* Riemann's Functional Equation - Directly calculates the value of
Zeta(s) for s < 2.
1. The first if statement handles the case when s < 0 and s is a
multiple of 2k. These are trivial zeroes where Zeta(s) is 0.
2. The second if statement handles the values of 0 < s < 2. Simpson's
method is used to numerically compute an approximation of the
definite integral.
3. The third if statement handles the values of -1 < s < 0. Recursion
is used alongside an approximation through Simpson's method.
4. The last if statement handles the case for s <= -1 and is not a
trivial zero. Recursion is used directly against the standard form
of Zeta(s).
*/
public static double riemannFuncForm(double s) {
double term = Math.pow(2, s)*Math.pow(Math.PI, s-1)*
(Math.sin((Math.PI*s)/2))*gamma(1-s);
if(s == 1.0 || (s <= -1 && s % 2 == 0) )
return 0;
else if (s >= 0 && s < 2)
return getSimpsonSum(s);
else if (s > -1 && s < 0)
return term*getSimpsonSum(1-s);
else
return term*standardZeta(1-s);
}
// Returns the function referenced inside the right hand side of the
// Cauchy-Schlomilch transformation for Zeta(s).
public static double function(double x, double s) {
double sech = 1 / Math.cosh(x); // Hyperbolic cosecant
double squared = Math.pow(sech, 2);
return ((Math.pow(x, s)) * squared);
}
// Simpson's rule - Approximates the definite integral of f from a to b.
public static double SimpsonsRule(double a, double b, double s, int n) {
double simpson, dx, x, sum4x, sum2x;
dx = (b-a) / n;
sum4x = 0.0;
sum2x = 0.0;
// 4/3 terms
for (int i = 1; i < n; i += 2) {
x = a + i * dx;
sum4x += function(x,s);
}
// 2/3 terms
for (int i = 2; i < n-1; i += 2) {
x = a + i * dx;
sum2x += function(x,s);
}
// Compute the integral approximation.
simpson = function(a,s) + function(a,b);
simpson = (dx / 3)*(simpson + 4 * sum4x + 2 * sum2x);
return simpson;
}
// Handles the error for for f(x) = t^s * sech(t)^2. The integration is
// done from 0 to 100.
// Stop Simspson's Method when the relative error is less than 1 * 10^-6
public static double SimpsonError(double a, double b, double s, int n)
{
double futureVal;
double absError = 1.0;
double finalValueOfN;
double numberOfIterations = 0.0;
double currentVal = SimpsonsRule(a,b,s,n);
while (absError / currentVal > 0.000001) {
n = 2*n;
futureVal = SimpsonsRule(a,b,s,n);
absError = Math.abs(futureVal - currentVal) / 15;
currentVal = futureVal;
}
// Find the number of iterations. N starts at 8 and doubles
// every iteration.
finalValueOfN = n / 8;
while (finalValueOfN % 2 == 0) {
finalValueOfN = finalValueOfN / 2;
numberOfIterations++;
}
System.out.println("The number of iterations is "
+ numberOfIterations + ".");
return currentVal;
}
// Returns an approximate sum of Zeta(s) through Simpson's rule.
public static double getSimpsonSum(double s) {
double constant = Math.pow(2, (2*s)-1) / (((Math.pow(2, s)) -2)*
(gamma(1+s)));
System.out.println("Did Simpson's Method.");
return constant*SimpsonError(0, 100, s, 8);
}
}
Would I have to change all of my double calculations to BigDecimal calculations in order to fix this?
Nope. All you would need to do is to catch and handle the NumberFormatException appropriately. Or, test for NaN and Inf before attempting to convert the double.
In this case, you are only using BigDecimal for formatting in "engineering" syntax. So another alternative would be to do the formatting directly. (Though I haven't found a simple way to do that yet.)
This error occurs with you because BigDecimal.valueOf(value) does not accept "NaN" "Not a Number" as parameter and the following expression will return NaN
Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2))*gamma(1-s)
this Math.pow(2, s)*Math.pow(Math.PI, s-1)*(Math.sin((Math.PI*s)/2)) will evaluate -0.0
and this function gamma(1-s) will evaluate "Infinity"
So -0.0 * Infinity equal NaN in java
please see this to know When can Java produce a NaN.
When can Java produce a NaN?

When compiling, I receive the error: "unreachable statement". How can I fix the issue?

public double Convertir(double Number) {
Number = nombre;
while ((Number - 365) >= 0) {
annee += 1; //this calculates the number of years
}
return annee;
double nombreSemaine = Number - (annee * 365);
while ((nombreSemaine - 7) >= 0) {
semaine = semaine + 1;
}//this calculates the number of weeks
return semaine;
double nombreJour = Number - (annee * 365) - (semaine * 7);
nombreJour = jour;
return jour;
}
With this code I am trying to convert a number written by the user,
which are days, into the number of years that it makes, the number of
weeks and the number of days. for example, number 365 should return 1
year 0 weeks 0 days.
return annee; returns annee so anything after this expression in the method won't get executed.
Perhaps you could return an Array instead:
public double[] Convertir(double Number) {
Number = nombre;
double[] all = new double[3];
while ((Number - 365) >= 0) {
annee += 1; //this calculates the number of years
}
all[0] = annee;
double nombreSemaine = Number - (annee * 365);
while ((nombreSemaine - 7) >= 0) {
semaine = semaine + 1;
}//this calculates the number of weeks
all[1] = semaine;
double nombreJour = Number - (annee * 365) - (semaine * 7);
nombreJour = jour;
all[2] = jour;
return all
}
or something similar. An ArrayList would probably be better...but it's the same general concept.
The code below return annee; won't be executed.
It looks like you want to return 3 values. You can only return 1 value, a double in this case.
Solution 1 (Global variables):
int annee, semaine, jour; //global variables
public void Convertir(int Number) { //I guess number should be an Int too, unless it's possible to pass 567.28 days...
//Number = nombre; Useless since this is a parameter
annee = (int)(Number/365);
semaine = (int)((Number - annee * 365)/7);
jour = Number - annee * 365 - semaine * 7;
}
Solution 2 (return an array):
public int[] Convertir(int Number) { //I guess number should be an Int too, unless it's possible to pass 567.28 days...
//Number = nombre; Useless since this is a parameter
int[] anneeSemaineJour = new int[3];
anneeSemaineJour[0] = (int)(Number/365);
anneeSemaineJour[1] = (int)((Number - anneeSemaineJour[0] * 365)/7);
anneeSemaineJour[2] = Number - anneeSemaineJour[0] * 365 - anneeSemaineJour[1] * 7;
return anneeSemaineJour;
}
You will then use it like this (Solution 2):
int[] resultat = convertir(822); // convertir(nombre) in your case I guess
System.out.println("Annee = " + resultat[0] + " Semaine = " + resultat[1] + " Jour = " + resultat[2]);
The problem is you have code (including another return) after a return statement. A return statement stops the function at that place and returns the value. Anything after that is unreachable.
Your code suffers from many problems.
Beside all what other have said (Everything below return won't be executed) you should be careful with your while loops, they are infinite loops:
while ((Number - 365) >= 0) {
annee += 1; //this calculates the number of years
}
If Number - 365 >= 0 then you're inside the while and you're adding 1 to annee, and this will not stop the loop since Number - 365 >= 0 will continue to be satisfied.
Same thing with your second loop.
"return" exits the method. If you want to return all of them (years, months, days) you can use an array. Your code had generally many mistakes, and similar operations were done on nombre (or Number as you had it) multiple times. I have tried to make to code runnable.
public double[] Convertir(double nombre) {
double[] yearsWeeksAndDays = new double[3];
double annee = 0;
double semaine = 0;
while (nombre >= 365) {
annee += 1; //this calculates the number of years
nombre -= 365;
}
yearsWeeksAndDays[0] = annee;
while (nombre >= 7) {
semaine = semaine + 1;
nombre -= 7;
}//this calculates the number of weeks
yearsWeeksAndDays[1] = semaine;
yearsWeeksAndDays[2] = nombre;
return yearsWeeksAndDays;
}
You need to wrap you 3 return values into a class and return that. Something like this ought to work:
public static void main(String[] args) {
System.out.println(convertir(365));
System.out.println(convertir(366.5));
System.out.println(convertir(456));
}
static class Duration {
int years;
int weeks;
double days;
#Override
public String toString() {
return years + " years, " + weeks + " weeks and " + days + " days.";
}
}
public static Duration convertir(double total) {
final Duration duration = new Duration();
duration.years = (int) (total / 365);
total = total % 365;
duration.weeks = (int) (total / 7);
total = total % 7;
duration.days = total;
return duration;
}
Output:
1 years, 0 weeks and 0.0 days.
1 years, 0 weeks and 1.5 days.
1 years, 13 weeks and 0.0 days.
Obviously it needs a little translation but French isn't my strong suit.
its throwing unrreachable code because compiler knows that when the controll reaches that return statement, then it would return and no more code would be executed.To solve this, what you could do is, either put the return statement in a condition block like i have shown below, but again this program wont return u the result you wanted. it will return only the year. if you want the entire result ie. number of years + number of weeks + number of days i would suggest you to make the entire answer to a single string and return.
public double Convertir(double Number) {
// Number = nombre;
double annee = 0;
double semaine = 0;
double jour = 0;
while ((Number - 365) >= 0) {
annee += 1; // this calculates the number of years
}
if (annee > 0) {
return annee;
}
double nombreSemaine = Number - (annee * 365);
while ((nombreSemaine - 7) >= 0) {
semaine = semaine + 1;
}// this calculates the number of weeks
if (semaine > 0)
return semaine;
double nombreJour = Number - (annee * 365) - (semaine * 7);
nombreJour = jour;
return jour;
}

Categories

Resources