【发布时间】:2015-06-24 04:12:18
【问题描述】:
这是我的 Java 入门课程的一个编程项目。我应该使用从文本文件输入的信息从终端运行程序。
我可以设置它,但它一直向我抛出一个无此类元素异常。异常发生在 while 循环的第二轮。我试图将所有输入放在同一行上,并尝试在每对之间添加一条额外的行。我也尝试删除额外的 input.nextLine()。
这里是个例外:
Enter the price or -1 to quit: $
Is this purchase a pet? y/n:
Enter the price or -1 to quit: $Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at DAG_PetDiscounterTester.main(DAG_PetDiscounterTester.java:33)
文件输入为:
23.56
n
178.97
n
395.88
是的
.98
n
1.97
n
57.89
是的
12.33
n
-1
引发异常的代码段是:
while((done == false) && (nItems < ARRAY_SIZE))
//While loop keeps the program going until user enters sentinel or array is full
{
Scanner input = new Scanner(System.in); //Create a scanner
System.out.printf("Enter the price or -1 to quit: $");
price = input.nextDouble();
//Inform user of required input and read it, assigning it to price
while((price <= 0) && (price != -1))
{
System.out.printf("Enter the price or -1 to quit: $");
price = input.nextDouble();
}
//If input is incorrect, continue to prompt until it is
if(price == SENTINEL) //If statement to check for sentinel
{
done = true; //Changing boolean value ends the program
}
else //If the program's not done, continue
{
input.nextLine(); //Clears newline character after price input
System.out.printf("Is this purchase a pet? y/n: ");
pet = input.nextLine();
//Informs user of next information needed and assigns input to pet boolean
while((!pet.equals("Y")) && (!pet.equals("y")) && (!pet.equals("N")) && (!pet.equals("n")))
//Verifies user input
{
System.out.printf("Is this purchase a pet? y/n: ");
pet = input.nextLine();
//If input is incorrect, continue to prompt until it is
}
if((pet.equals("Y")) || (pet.equals("y")))
//Decision statement determines what value to assign to pet boolean
{
isPet[nItems] = true;
}
else
{
isPet[nItems] = false;
}
prices[nItems] = price; //Assigns current item's price to prices array
nItems++; //Increments items counter to track number of items in the arrays
}
}
它具体发生在 price = input.nextDouble()。
任何建议将不胜感激。
【问题讨论】:
标签: java exception file-io java.util.scanner