1

I'm attempting to be slick and store user inputs from the console into an array but I'm getting an error when I try to execute. See code and error below. import java.util.Scanner;

public class Investment {

public static float futureInvestmentValue;
public static float investmentAmount;
public static float monthlyInterestRate;
public static float numberofYears;
public static float userInputValues[] = new float[3];

public static void main(String[] args) {

    showPrompt("Enter investment amount:");
    readInput(0);
    showPrompt("Enter annual interest rate as a percentage:");
    readInput(1);
    showPrompt("Enter number of years:");
    readInput(2);
}


private static void showPrompt(String prompt){
    System.out.print(prompt);
}

private static void readInput(int i){
    Scanner userInput = new Scanner(System.in);
    userInputValues[i] = userInput.nextFloat();
    userInput.close();
}


}

When I run this, I can input the investment amount, but I when it gets to teh prompt for the interest rate, I get:

Enter annual interest rate as a percentage:Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextFloat(Unknown Source)
    at Investment.readInput(Investment.java:29)
    at Investment.main(Investment.java:17)
Vihar
  • 3,626
  • 2
  • 24
  • 47
Bob Wakefield
  • 3,739
  • 4
  • 20
  • 30
  • making a new scanner instance for every read is not a good idea – Vihar Aug 20 '15 at 05:29
  • The other question that is supposed to answer this one does not use arrays which I thought was the problem. The problem is opening and closing the new scanner which I was able to figure out from the other question. – Bob Wakefield Aug 20 '15 at 06:08

0 Answers0