【发布时间】:2014-03-30 20:21:06
【问题描述】:
我的程序在这段代码中抛出 StringIndexOutOfBoundsException:temp1 = temp.replace('-', temp.charAt(p)); 我正在尝试获取相同字母的索引(在比较输入的字母和单词之后)并删除“-”以表明用户猜对了.** **我已经尝试了几个小时无济于事。我认为问题在于我的循环。感谢您的回答:)如果我违反了什么,请原谅我。
run: ----- Enter a letter: a Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range:3 在 java.lang.String.charAt(String.java:658) 在 Hangman.main(Hangman.java:34) Java 结果:1
import java.util.Scanner;
public class Hangman {
public static void main (String [] args){
Scanner sc = new Scanner(System.in);
String word = "Sample";
String temp = null;
String temp1 = null;
String letter = null;
int n;
int m=0;
int p = 0;
for (n = 0; n<word.length(); n++){
temp = word.replaceAll(word, "-"); //replaces the String word with "-" and prints
System.out.print(temp);
}
while (m<=5){ //the player can only guess incorrectly 5 times
System.out.println("\nEnter a letter:");
letter = sc.nextLine();
letter.toLowerCase();
if (word.contains(letter) == true){
p = word.indexOf(letter);
temp1 = temp.replace('-', temp.charAt(p)); //if the word contains the letter, "-" is replaced by the letter.
System.out.print(temp1);
}
else {
System.out.print("\nMissed: "+letter); //if not, Missed: +the given letter
m++; //to count for incorrect guesses
}
System.out.print(temp1);
}
System.out.println("Game Over.");
}
}
【问题讨论】:
-
temp1 = temp.replace('-', temp.charAt(p));在这一行中,使用 word.charAt(p) 代替 temp.charAt(p) 因为 temp 是 ----- 而不是在您编写 temp = word.replaceAll(word, "-"); 时采样这将帮助你.....
-
啊,是的,我现在可以看到了。所以我尝试替换 temp1 = temp.replace('-', temp.charAt(p));到 temp1 = temp.replace('-',word.charAt(p));。但这就是发生的事情: ------ 输入一个字母: a aa 输入一个字母: 它只打印到索引。我似乎无法正确实现“char by char print”,我认为这可能会解决这个问题。
-
打印两次因为你在写 System.out.print(temp1); if (m
标签: java string for-loop while-loop indexoutofboundsexception