我正在創建一個程序,它將文件名作爲參數並在文本中檢查迴文。該程序還將根據用戶輸入替換字母或根據用戶輸入刪除單詞。出於某種原因,掃描儀在數組列表中的掃描程序錯誤
public void letter
and
public void word
無法正常工作。
這是我在程序運行和用戶類型後收到錯誤:
What would you like to do? Here are your options:
Press 1 to Print all palindromes
Press 2 to Replace any letter
Press 3 to remove all occurences of a word
Press 4 to exit
2
What letter would you like to remove?
e
What letter would you like to add?
r
[ ]
What would you like to do? Here are your options:
Press 1 to Print all palindromes
Press 2 to Replace any letter
Press 3 to remove all occurences of a word
Press 4 to exit
這是錯誤,我得到
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at Homework6.main(Homework6.java:28)**
代碼:
import java.util.ArrayList;
import java.util.Scanner;
import java.util.*;
import java.io.File;
public class Test {
static ArrayList<String> strings = new ArrayList<String>();
public static void main(String[] args) {
Test test2 = new Test();
try {
Scanner scanner = new Scanner(new File(args[0]));
while (scanner.hasNext()) {
strings.add(scanner.next());
}
} catch (Exception e) {
}
//ArrayList<String> a = new ArrayList<String>(strings);
while (true) {
System.out.println("\nWhat would you like to do? Here are your options: \nPress 1 to Print all palindromes \nPress 2 to Replace any letter \nPress 3 to remove all occurences of a word \nPress 4 to exit\n");
Scanner s = new Scanner(System.in);
String command = s.next();
if (command.equals("1")) {
test2.pal();
} else if (command.equals("2")) {
test2.letter();
} else if (command.equals("3")) {
test2.word();
} else if (command.equals("4")) {
System.exit(0);
}
}
}
public void pal() {
int a;
int c;
// boolean isPalindrome() ;
for (a = 0; a < strings.size(); a++) {
String replace = strings.get(a);
replace = replace.replaceAll("[.,']", "");
}
for (c = 0; c < strings.size(); c++) {
boolean pal = PalindromeChecker.isPalindrome(strings.get(c));
if (true) {
System.out.print(strings.get(c));
}
}
}
public void letter() {
int b;
Scanner replaceLetter = new Scanner(System.in);
System.out.println("What letter would you like to remove?");
String badLetter = replaceLetter.next();
System.out.println("What letter would you like to add?");
String newLetter = replaceLetter.next();
for (b = 0; b < strings.size(); b++) {
String replaceVowels = strings.get(b);
replaceVowels = replaceVowels.replace("badVowel", "newVowel");
}
replaceLetter.close();
System.out.print(strings);
}
public void word() {
Scanner removeWord = new Scanner(System.in);
System.out.println("What word would you like to remove?");
String word = removeWord.next();
strings.remove(word);
removeWord.close();
System.out.print(strings);
}
}