所以我有这段代码:
package nmishewa.geekycamp.dictionary;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static File file = new File( "C:\\Users\\N\\workspace\\Dictionary\\src\\nmishewa\\geekycamp\\dictionary\\bg_utf8.txt");
public static int value = 1;
private static Scanner input;
public static Scanner in = new Scanner(System.in);
public static Map<String, Integer> map = new HashMap<String, Integer>();
public static void main(String[] args) throws FileNotFoundException {
readFile();
System.out.println("Enter number of function wanted" + "\n1 to add"
+ "\n 2 for searching by prefix" + "\n for deleting");
int choice = in.nextInt();
if (choice == 1) {
add();
}
if (choice == 2) {
prefixSearch();
}
if (choice == 3) {
remove();
}
}
public static void readFile() throws FileNotFoundException {
input = new Scanner(file);
boolean done = false;
int value = 1;
while (input.next() != null) {
String word = input.next().toLowerCase();
String[] line = word.split("[,\\s]+");
for (int j = 0; j < line.length; j++) {
map.put(line[j], value);
value++;
done = true;
}
}
if (done == true) {
System.out.println("Succes");
}
}
public static void prefixSearch() {
System.out.println("Enter prefix");
String prefix = in.next().toLowerCase();
for (Map.Entry<String, Integer> key : map.entrySet()) {
if (key.getKey().startsWith(prefix)) {
System.out.println(key.getKey());
}
}
}
public static void add() {
System.out.println("Enter words you wish to add");
boolean done = false;
while (in.next() != null) {
String word = in.next().toLowerCase();
String[] line = word.split("[,\\s]+");
for (int j = 0; j < line.length; j++) {
if (!map.containsKey(line[j])) {
map.put(line[j], value);
value++;
done = true;
} else {
continue;
}
}
}
if (done == true) {
System.out.println("Succes");
}
}
public static void remove() {
System.out.println("Enter words you want to remove");
boolean done = false;
while (in.next() != null) {
String word = in.next().toLowerCase();
String[] line = word.split("[,\\s]+");
for (int j = 0; j < line.length; j++) {
if (map.containsKey(line[j])) {
map.remove(line[j], map.get(line[j]));
value--;
done = true;
} else {
continue;
}
}
}
if (done == true) {
System.out.println("Succes");
}
}
}`
然后抛出
` Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at nmishewa.geekycamp.dictionary.Main.readFile(Main.java:41)
at nmishewa.geekycamp.dictionary.Main.main(Main.java:18)`
带有单词的文件看起来像这样 а аба абаджийски абаджийство абаджия абажур 任何人都知道为什么会这样,以及如何解决它?
答案 0 :(得分:0)
用下面的删除方法替换你的while循环条件。
使用while (input.hasNext())
代替while(input.next() != null)
答案 1 :(得分:0)