1) Change the program so that the user has to enter the initial balance and the interest rate. Assume that the user will enter interest rates in whole numbers ("5" would represent an interest rate of 5%, for example). Assume that the user will enter initial balances that are numeric only - no commas. 2) Change the code to display how many years it takes an investment to triple.

I have entered my scanner so the user can input their balance and interest. no matter what user enters it outputs 2000.

 import java.util.Scanner;
public class InvestmentRunner
{
 public static void main(String[] args)
{ 
  Scanner in = new Scanner(System.in);
  System.out.print("Please Enter Initial Balance:");
  String Balance = in.next();
  System.out.print("Please Enter Interest Rate:");
  String Interest = in.next();

  final double INITIAL_BALANCE = 10000;
  final double RATE = 5;
  Investment invest = new Investment(INITIAL_BALANCE, RATE);
  invest.waitForBalance(2 * INITIAL_BALANCE);
  int years = invest.getYears();
  System.out.println("The investment doubled after "
        + years + " years");


  }   
}  
有帮助吗?

解决方案

Per the question askers comment: well no matter what the user inputs the output stays at 2000

These are the lines in which you're constructing an Investment object, calling methods on this object, and then printing the value.

Investment invest = new Investment(INITIAL_BALANCE, RATE);
invest.waitForBalance(2 * INITIAL_BALANCE);
int years = invest.getYears();
System.out.println("The investment doubled after " + years + " years");

You haven't posted the Investment class, so I just have to assume these methods are fine. The PROBLEM is here:

final double INITIAL_BALANCE = 10000;
final double RATE = 5;

These are the variables you're sending to the Investment constructor. Constants you've hardcoded in. Meanwhile, this is where you take user input:

System.out.print("Please Enter Initial Balance:");
String Balance = in.next();
System.out.print("Please Enter Interest Rate:");
String Interest = in.next();

You take the Balance (should be balance), then take Interest (should be interest), then you do nothing with these values. You need to parse a double out of these Strings and then send them as the arguments to your constructor.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top