I am trying to code the below snippet in Java 8 -
Scanner sc = new Scanner(System.in);
System.out.println("Enter the policy amount: ");
long amount = sc.nextInt();
System.out.println("Enter the interest: ");
int interest = sc.nextInt();
System.out.println("Enter the number of years: ");
int years = sc.nextInt();
sc.close();
for (int i = 1; i <= years; i++) {
result = nextYear + amount;
calculateInterest = result * interest / 100;
nextYear = result + calculateInterest;
}
return nextYear;
I need the nextYear value so, have tried like below using IntStream
IntStream intStream = IntStream.rangeClosed(1, years);
intStream.forEach(num -> {
result = nextYear + amount;
calculateInterest = result * interest / 100;
nextYear = result + calculateInterest;
});
but, not sure how to return the nextYear value. How to handle this or is there any other way to do this. kindly suggest. Thank you.
forloops... nothing wrong with them. I would only usestreamsif the code can be better expressed withstreams(or for fun/testing) - very opinion-based