import java.io.*;
class empl
{
int p, n, r, i;
void accept()
{
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Principal amount");
int p = Integer.parseInt(br.readLine());
System.out.println("Enter no of years");
int n = Integer.parseInt(br.readLine());
System.out.println("Enter rate");
int r = Integer.parseInt(br.readLine());
} catch(Exception e)
{
System.out.println("" + e);
}
}
int calculate()
{
i = (p * n * r) / 100;
return (i);
}
}
class bank
{
public static void main(String args[])
{
empl e = new empl();
e.accept();
int a = e.calculate();
System.out.println("i=" + a);
}
}
I am a beginner in java.The above program always gives me result as 0.I have also tried many different input values but the result remains the same.I am sure that that there is no problem in formula.Please help me out.Thanks in advance.
Your accept
method declares new local variables for p
, n
and r
- it doesn't assign values to the instance variables, which will still have a value of 0. Rather than declaring local variables, you should just assign values to the instance variables. So for example, this line:
int p = Integer.parseInt(br.readLine());
should be:
p = Integer.parseInt(br.readLine());
Additionally, there's the fact that the arithmetic is entirely performed in integer maths, as others have pointed out. That doesn't matter if you really want an integer result (e.g. if you don't mind getting 0 as a result when p
, n
and r
are all 10) - but if you want to be able to get non-integer results, you probably want something like:
double calculate() {
return (p * n * r) / 100.0;
}
... or perhaps use BigDecimal
instead, if the exact digit values are important to you. (double
is appropriate for natural quantities such as height and weight; BigDecimal
is appropriate for financial calculations. Search for questions on double
and BigDecimal
for more information about this.)
See more on this question at Stackoverflow