Search code examples
javafor-loopnetbeanssystem.outmoney-format

using the NumberFormat import in System.out.format


I'm doing a program on compound interest for a school assignment. I tried using System.out.format(); and used money.format to format the variables investment, interest, and investTotal. I don't know why but it keeps on throwing me an error for "Invalid value type 'String' for format specifier '%.2f', parameter 2, 3, and 4" I've been trying to figure this out for quite a while now and I still can't seem to find why it is.

-- A

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // SPLASH 
    // CONSTANT 
    // OBJECT 
    Scanner input = new Scanner(System.in); 
    NumberFormat money = NumberFormat.getCurrencyInstance();

    // VARIABLES
    double investment; 
    double investTotal; 
    double rate; 
    double intrest; 
    int year; 

    // INPUT 
    do 
    {
        System.out.print("Enter yearly investment (min $100.00 deposit): ");
        investment = input.nextDouble(); 
    } 
    while (investment < 100); 

    do 
    {
        System.out.print("Enter intrest rate (%): ");
        rate = input.nextDouble()/100;
    } 
    while (rate <= 0); 

    do
    {
        System.out.print("Enter number of years: ");
        year = input.nextInt(); 
    }
    while (year <= 0 || year > 15);  

    // PROCESSING 
    investTotal = investment;
    for (int perYear = 1; perYear <= year; perYear++)
    {
        intrest = investTotal*rate;
        investTotal = (investment+intrest);
        System.out.format("%2s | %.2f | %.2f | %.2f\n", perYear, money.format(investment), money.format(intrest), money.format(investTotal));
        investTotal = investTotal + investment;
    }
    // OUTPUT 
}

}


Solution

  • getCurrencyInstance returns a String and therefor can't be formatted using %.2f.

    You better look how NumberFormat works: https://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html

    As you can see, the result of the formatting is a String, when you are using String.format with %.2f you should enter a number e.g: System.out.format("%2s | %.2f\n", 1.001, 1.005);

    I'm not sure what are you trying to get using the NumberFormat, if you classify I will be able to help you further with this question.