我开发了一个99%完成的刽子手游戏。我只有一个小故障,故障是当用户没有输入猜测并按下输入时。
我知道我们无法检查字符是否为空,因此我使用scanner.nextLine().isEmpty()
检查字符串是否为空。现在,如果我没有输入任何东西,我按回车然后它工作正常并输出打印行消息。
但是,如果我输入一封信并按回车键,那么它会转到下一行,它要我输入一些东西。如果我输入另一个字母,那么它工作正常,如果我什么都不输入并按回车然后我得到一个例外
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
所以我相信我的问题是if语句,我检查字符串是否为空,如果没有,则转到检查字符:
if (scanner.nextLine().isEmpty()) {
System.out.println("Your guess seems empty. Please enter in a letter or number");
} else {
char input = scanner.nextLine().charAt(0);
if (input == '-' || Character.isLetter(input) || Character.isDigit(input)) {
if (input == '-') {
weArePlaying = false;
wordCompleted = true;
}
....
}
如何摆动这个以便如果空字符串然后要求用户再次猜测,如果不是空的则继续猜测?
以下是更多代码:
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> movieList = new ArrayList<>();
File file = new File("C:\\Users\\mmkp1\\Documents\\listofmovies.txt");
Scanner fileScanner = new Scanner(file);
int attempts = 10;
Scanner scanner = new Scanner(System.in);
Random random = new Random();
ArrayList<Character> guessedLetters = new ArrayList<>();
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
// Reads the whole file
movieList.add(line);
}
boolean weArePlaying = true;
while (weArePlaying) {
System.out.println("Welcome to Guess The Movie Game");
int index = random.nextInt(movieList.size());
String getMovies = movieList.get(index);
char[] randomWordToGuess = getMovies.toLowerCase().toCharArray();
int wordLength = randomWordToGuess.length;
char[] playerGuess = new char[wordLength];
boolean wordCompleted = false;
for (int i = 0; i < playerGuess.length; i++) {
playerGuess[i] = '_';
}
for (int i = 0; i < randomWordToGuess.length; i++) {
if (randomWordToGuess[i] == ' ') {
playerGuess[i] = ' ';
}
}
while (!wordCompleted && attempts != 0) {
printArray(playerGuess);
System.out.println("Number of attempts left: " + attempts);
System.out.println("Your previous guesses were:" + guessedLetters);
System.out.println("Enter a letter or number");
if (scanner.nextLine().isEmpty()) {
System.out.println("Your guess seems empty. Please enter in a letter or number");
} else {
char input = scanner.nextLine().charAt(0);
if (input == '-' || Character.isLetter(input) || Character.isDigit(input)) {
if (input == '-') {
weArePlaying = false;
wordCompleted = true;
}
....
}
答案 0 :(得分:2)
您使用扫描仪错误并拨打nextLine()
两次。
if (scanner.nextLine().isEmpty()) { // First call.
System.out.println("empy");
}
else {
char input = scanner.nextLine().charAt(0); // Second call.
}
让我们说扫描仪对我们来说很有意思。 第一次调用将获取它,看到它不是空的并将其扔掉。 第二次调用将不会获得我们感兴趣的行,但会尝试获取(可能为空)后续行。
尝试访问空字符串的第一个字符会导致您发布的StringIndexOutOfBoundsException
。
您可以使用局部变量轻松修复代码,如下所示:
String line;
char input;
line = scanner.nextLine();
if (line.isEmpty()) {
System.out.println("empy");
return;
}
input = line.charAt(0);
// ...