当我再次通过for循环时,我正在获取NoSuchElementException
。在对代码进行一些更改之前,我能够循环而没有问题。我必须在方法setRiskAmount()
中移动用户输入,而不是在此类中使用相同的Scanner
对象来读取该输入。那时我开始发现错误。我知道从Scanner
没有东西可以读取异常,我只是不确定为什么在这种情况下或如何调整我的代码。NoSuchElementException当使用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();
}
请输入保险类型(房产,汽车,旅游)或quit退出
物业请输入风险金额为财产保险>> 25000 ****** ************物业保险费率为:0.25风险金额为25000.0财产保险费为:6250.0 ***************** *请输入保险类型(Property,Auto,Travel)或退出>>线程“main”中的异常 java.util。 NoSuchElementException异常:没有在在 UseInsurance.main(UseInsurance.java:25) java.util.Scanner.nextLine(来源不明)发现线
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();
}
}
这样做。谢谢! – user2057488