使用Scanner对象并在循环中迭代时出现NoSuchElementException

时间:2016-05-15 03:43:18

标签: java nosuchelementexception

我第二次进入for循环时,目前正在获得NoSuchElementException。在对代码进行一些更改之前,我能够循环没有问题。我不得不在方法setRiskAmount()中移动用户输入,而不是使用此类中的相同Scanner对象来读取该输入。那是我开始收到错误的时候。我知道当Scanner无法读取任何内容时会抛出异常,我不知道为什么会出现这种情况或者如何调整代码。

更新: 如果我删除了setRiskAmount()方法中的所有代码,我就不会再出错了,在下一次迭代中,我能够读取用户输入。我是用不同的方式做的,它工作得非常好。我做了更改,以满足我的申请的某些要求。

@Override
void setRiskAmount() {
    // Ask for user input using a Scanner

    Scanner input = new Scanner(System.in);
    System.out.print("Please enter risk amount for Property Insurance >> ");
    riskAmount = input.nextFloat();
    input.close();
}
  

请输入保险类型(物业,自动,旅行)或退出退出

     
    
      

财产请输入财产保险的风险金额>> 25000       ******************财产保险费率为:0.25风险金额为25000.0财产保险费为:6250.0       ******************请输入保险类型(物业,自动,旅行)或退出退出>>线程" main"中的例外情况       java.util.NoSuchElementException:找不到行       java.util.Scanner.nextLine(未知来源)at       UseInsurance.main(UseInsurance.java:25)

    
  
public class UseInsurance {

    public static void main(String[] args) {
        // The Scanner object will be used for user input
        Scanner input = new Scanner(System.in);

        String t = "";

        // Create the user interface
        // Loop will continue looping until the user decides to exit
        for (int i = 10; i > 0; i++) {
            System.out.println("Please enter insurance type (Property, Auto, Travel) or QUIT to exit >> ");
            t = input.nextLine();
            if (t.equals("Property")) {
                // Create an instance of PropertyInsurance, set the object name and type, ask for user input for risk amount 
                // calculate and add to the total quote. Display the results.

                PropertyInsurance pInsurance = new PropertyInsurance("Property");
                pInsurance.setInsuredObjectName();
                pInsurance.setRiskAmount();
                InsuranceAgentApp.totalPremium += pInsurance.getPremium();
                pInsurance.display();
            } else if (t.equals("Auto")) {
                // Create an instance of AutomobileInsurance, set the object name and type, ask for user input for risk amount 
                // calculate and add to the total quote. Display the results.
                AutomobileInsurance aInsurance = new AutomobileInsurance("Auto");
                aInsurance.setInsuredObjectName();
                aInsurance.setRiskAmount();
                InsuranceAgentApp.totalPremium += aInsurance.getPremium();
                aInsurance.display();
            } else if (t.equals("Travel")) {
                // Create an instance of TravelInsurance, set the object name and type, ask for user input for risk amount 
                // calculate and add to the total quote. Display the results.
                TravelInsurance tInsurance = new TravelInsurance("Travel");
                tInsurance.setInsuredObjectName();
                tInsurance.setRiskAmount();
                InsuranceAgentApp.totalPremium += tInsurance.getPremium();
                tInsurance.display();
            } else if ((t.equals("QUIT")) || (t.equals("quit")) || (t.equals("Quit"))) {
                // Exit the loop upon the user typing QUIT, quit or Quit

                break;
            } else {
                // If none of the above options are selected, display a message
                // and loop again.

                System.out.println("Invalid input");
            }
        }

        // Display the amount of the total quote
        System.out.println("The total quote is " + InsuranceAgentApp.totalPremium);
        // Close the Scanner object
        input.close();

    }

}

4 个答案:

答案 0 :(得分:1)

问题是您在报价后关闭输入,只需删除该行。此外,我提供了一些可能更适合您的代码,因为它更清晰,更整合。我留下评论来解释我的所作所为。

        Boolean done = false; //Boolean variable to monitor loop without increments

        // Create the user interface
        // Loop will continue looping until the user decides to exit
        while(!done){
            System.out.println("Please enter insurance type (Property, Auto, Travel) or QUIT to exit >> ");
            t = input.nextLine();
            t = t.toUpperCase();//normalizes the string to all upercase letters
            switch(t){
                case "PROPERTY":
                    //your code
                case "AUTO":
                    //your code
                case "TRAVEL":
                    //your code
                case "QUIT":
                    done = true;//loop wil exit when done is true

                default:
                    System.out.println("Invalid Input");
                    }


        }

答案 1 :(得分:0)

问题出在setRiskAmount()。当您从Scanner关闭System.in阅读时,它不仅会关闭该Scanner,还会关闭System.in。这可以防止主方法中的ScannerSystem.in读取任何进一步的输入。

解决方案是简单地删除关闭此Scanner的行。如果有可能在以后的代码中Scanner必须读取任何输入,则永远不要关闭System.in的{​​{1}}读数。

答案 2 :(得分:0)

public class Test {
static float riskAmount;
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {  
    for (int i = 0; i < 10; i++) {
        setRiskAmount();
        if(i==9){
            System.out.println("Total Risk Amount is: "+ riskAmount); 
        }
    }   
}
static void setRiskAmount() {
    System.out.print("Please enter risk amount for Property Insurance >> ");
    riskAmount+= input.nextFloat();
} }

我为你做这件事会有1000%的效果。只需要声明Scanner全局。

答案 3 :(得分:0)

public class Test {
static float riskAmount;
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {  
    for (int i = 0; i < 10; i++) {
        setRiskAmount();
        if(i==9){
            System.out.println("Total Risk Amount is: "+ riskAmount);
            input.close();
        }
    }   
}
static void setRiskAmount() {
    System.out.print("Please enter risk amount for Property Insurance >> ");
    riskAmount+= input.nextFloat();
} }