user311302
user311302

Reputation: 97

How do I change an int to a double in this code?

I'm trying to run a program which calculates balance after interest. I easily got it to run with:

public class bigjavach1p7balprob{
  public static void main(String[] args){
    double balance = 10000.0;
    int year = 0;

    while (balance < 20000){
      year += 1;
      double interest = balance * .05;
      balance = balance + interest;

      System.out.println("year " + year + ": " + balance);

    }
  }
}

but I want to have balance as an int first, and then convert it to double when the interest is added. I have:

import java.util.*;

public class bigjavach1p7balprob{
  public static void main(String[] args){
    int balance = 10000;
    int year = 0;

    while (balance < 20000){
      year += 1;
      double interest = (double)balance * .05;
      balance = Integer.parseInt(balance) + interest;

      System.out.println("year " + year + ": " + balance);

    }
  }
}

This isn't compiling or running.

Upvotes: 0

Views: 79

Answers (1)

Arthur
Arthur

Reputation: 1246

The reason for the compilation error is that Integer.parseInt() takes in a String not a int.

If you wanted to change the balance to a whole number (integer) you could cast it to an int (even if it's a double):

balance = (int) (balance + interest)

But you can't actually change the variable type.

Upvotes: 1

Related Questions