使用扫描仪以数组存储用户输入的正确方法是什么?

时间:2015-08-20 05:28:14

标签: java arrays

我试图光滑并将用户输入从控制台存储到阵列中,但是当我尝试执行时我收到错误。请参阅下面的代码和错误。 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();
}


}

当我运行时,我可以输入投资金额,但是当我得到利率提示时,我得到:

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)

0 个答案:

没有答案