所以我有个密码:
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)`这个带有文字的文件看起来像这个аабаабаджийскиабаджийствоабаджияабажур,有人知道为什么会发生这种情况,以及如何解决它?
发布于 2014-09-07 16:31:57
在remove方法中替换with循环条件,如下所示。
使用while (input.hasNext())而不是while(input.next() != null)
发布于 2014-09-07 16:36:11
在调用next时,您应该检查扫描仪是否有。
if(input.hasNext())
input.next();参考扫描仪
https://stackoverflow.com/questions/25712333
复制相似问题