user147219
user147219

Reputation: 375

Java compiler is telling me I have not initiated variable "interest" or "pmt"

I am trying to program an amortization calculator in which the user can enter a value for balance, a value for their interest rate in decimal form, and a value for monthly payment. With this information I want to output an interest amount in dollars, a principal amount, and a new balance. Here is my code:

import java.util.Scanner;
public class Amortization{
   public static void main(String []args){
      Scanner pmt, interest, balance = new Scanner(System.in);
      System.out.println("What is your balance?");
      double b = balance.nextDouble();
      System.out.println("What is your interest rate in decimal?");
      double i = interest.nextDouble();
      System.out.println("What is your monthly payment?");
      double p = pmt.nextDouble();
      double pv = p-(b*i);
      System.out.println("Your interest amount is " + (b*i));
      System.out.println("Your principal amount is " + pv);
      System.out.println("Your new balance is " + (b-pv));
   }
}

Upvotes: 0

Views: 67

Answers (2)

sirandy
sirandy

Reputation: 1838

As @nhouser9 says, you don't need three scanners and answering your question the compiler says that the variables are not initialized because you are only initializing the last of them (balance). Multiple initializing in java won't functions as you expected (initialize all the variables with the same value).

Upvotes: 0

nhouser9
nhouser9

Reputation: 6780

You should not declare 3 scanners to read from the standard input. Declare one and just keep reading from it. Like this:

import java.util.Scanner;
public class Amortization{
   public static void main(String []args){
      Scanner input = new Scanner(System.in);
      System.out.println("What is your balance?");
      double b = input.nextDouble();
      System.out.println("What is your interest rate in decimal?");
      double i = input.nextDouble();
      System.out.println("What is your monthly payment?");
      double p = input.nextDouble();
      double pv = p-(b*i);
      System.out.println("Your interest amount is " + (b*i));
      System.out.println("Your principal amount is " + pv);
      System.out.println("Your new balance is " + (b-pv));
   }
}

The main point here is that a scanner is the object that reads from an input stream, not the value being read. You don't need a new scanner for every value you want to read.

Upvotes: 1

Related Questions