for Loops
|
for (initialization;
condition;
update)
Equivalent to
|
Example: Add one more method to Investment class
/**
Keeps accumulating interest for a given number of years.
@param n the number of years
*/
public void waitYears(int n)
{
for (int i = 1; i <= n; i++)
{
double interest = balance * rate / 100;
balance = balance + interest;
}
years = years + n;
}
|
![]() |
import java.util.Scanner;
public class Sum
{
public static void main(String[] args)
{
int A, total=0;
Scanner in = new Scanner(System.in);
for(int i=0; i<5; i++)
{
System.out.println("Enter a number");
A = in.nextInt();
total = total + A; //total += A;
}
System.out.println('\n'+ "The total is "+ total + ".");
}
}
A semicolon that shouldn't be there:
|