我的方法运行,但执行一次后出现异常。我不明白为什么。第 24 行,即异常中指出的行,位于“choice=in.nextInt();”处
这是我的例外:
1 找到一个项目。
2 显示所有项目。
3 更新项目。
4 将项目保存到磁盘。
5 退出。
1
您选择从文件中查找项目。
输入您要查找的 DVD 的 sku。
857295
857295 Star.Wars 152
1 查找项目。
2 显示所有项目。
3 更新项目。
4 将项目保存到磁盘。
5 退出。 java.util.Scanner.next(Unknown Source) 处 java.util.Scanner.throwFor(Unknown Source) 处 java.util.Scanner.nextInt(Unknown Source)处
的线程“main”java.util.NoSuchElementException 异常 。 util.Scanner.nextInt(未知来源)
在 version4.version4.main(version4.java:24)
这是我的代码:
import java.util.*;
import java.io.*;
public class version4
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner in = new Scanner(System.in);
boolean exit = false;
int choice = 0;
while (!exit)
{
System.out.println("1 Find an item.\n2 Display all items.\n3 Update item.\n4 Save item to disk.\n5 Quit.");
choice = in.nextInt();
switch (choice){
case 1: System.out.println("You chose to find an item from file."); findItem(); break;
case 2: System.out.println("You chose to display all items."); readDisplay(); break;
case 3: System.out.println("You chose to update an item."); itemUpdate(); break;
case 4: System.out.println("You chose to save an item to disk."); itemAdd(); break;
case 5: exit = true; in.close(); break;
default: System.out.println("That is not a valid option."); break;
}
}
System.out.println("Goodbye.");
}
public static void findItem() throws FileNotFoundException {
FileReader reader = new FileReader("read_record.txt");
Scanner fin = new Scanner(reader);
String str = null;
ArrayList<String> dvdfile = new ArrayList<String>();
if (fin != null && fin.hasNext()) { // do we have a scanner, is there anything to read?
while (fin.hasNext()) { // while there's something to read...
str = fin.next(); // read it.
if (str == null) { // end if it's null
break;
}
dvdfile.add(str); // otherwise add it.
}
} fin.close();
Scanner kb = new Scanner(System.in);
System.out.println("Enter the sku of the dvd you wish to find.");
String dvdSku = kb.next();
int index = dvdfile.indexOf(dvdSku);
// Finds the dvd that matches sku entered, and prints out its attributes under correct rows.
String skuToFind = dvdfile.get(index); String titleToFind = dvdfile.get(index+1); String lengthToFind = dvdfile.get(index+2);
System.out.printf("%-10s %-15s %10s %n",skuToFind,titleToFind,lengthToFind);
kb.close();
}