October 3rd, 2012, 12:01 PM
-
Please help me understand classes?
Why can't I do this:
Main:
Code:
public class TestInvestment {
public static void main(String[] args) {
FutureInvestmentValue fiv = new FutureInvestmentValue();
fiv.investment(a,b,y);
}
}
Class:
Code:
import java.util.Scanner;
public class FutureInvestmentValue {
public double investment(double a, double b, int y){
Scanner input = new Scanner(System.in);
System.out.println("Enter invest amount ");
a = input.nextDouble();
System.out.println("Enter intrest rate ");
b = input.nextDouble();
System.out.println("Enter how many years ");
y = input.nextInt();
return a + (y*(a * b));
}
}
I'm getting an error in eclipse:
a cannot be resolved
b cannot be resolved
y cannot be resolved
Can't I pass the user input to the method??
October 3rd, 2012, 12:24 PM
-
Java is pass-by-value. That means changing the values of parameters in a method will not be reflected back to the caller. While technically legal, the IDE is assuming you really are trying to use different variable names which you have not declared. You don't need to pass anything:
Code:
public class TestInvestment {
public static void main(String[] args) {
FutureInvestmentValue fiv = new FutureInvestmentValue();
double result=fiv.investment();
}
}
Code:
public class FutureInvestmentValue {
public double investment(){
double a;
double b;
int y;
Scanner input = new Scanner(System.in);
System.out.println("Enter invest amount ");
a = input.nextDouble();
System.out.println("Enter intrest rate ");
b = input.nextDouble();
System.out.println("Enter how many years ");
y = input.nextInt();
return a + (y*(a * b));
}
Last edited by gw1500se; October 3rd, 2012 at 01:10 PM.
There are 10 kinds of people in the world. Those that understand binary and those that don't.
October 3rd, 2012, 12:55 PM
-
OHHH, I was soo close, yet so far away. 
I had too many parameters, DOH!
Thanks for the reply, this OOP is so new to me.
October 3rd, 2012, 01:09 PM
-
Its a little hard to get your head around (at least it was for me) but once you do, you'll understand how it makes life easier.
There are 10 kinds of people in the world. Those that understand binary and those that don't.