所以我想将用户输入转换为变量然后将其添加到数组中,而是将字符直接插入数组并跳过3行代码。 这里的守则
import java.util.*;
public class Hangman{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your word and press enter: ");
String word = sc.nextLine();
System.out.println("Please enter a relevant category and press enter: ");
String category = sc.nextLine();
word.toUpperCase();
char charArray[] = new char[word.length()];
for(int i = 0; i<=word.length(); i++){
System.out.println("Category: " + category);
System.out.println("Letters Guessed: " + Arrays.toString(charArray));
System.out.println("Your guess: ");
char guess = sc.nextLine().charAt(0);
compare(guess, word);
charArray[i] = guess;
}
}
public static boolean compare(char guess, String word){
for(int i = 0; i<word.length(); i++){
if(guess == word.charAt(i)){
return true;
}
}
return true;
}
}
输出:
Please enter your word and press enter:
hello
Please enter a relevant category and press enter:
test
Category: test
Letters Guessed: [hi
Category: test
Letters Guessed: [h, l
Category: test
Letters Guessed: [h, l, m
Category: test
Letters Guessed: [h, l, m, o
Category: test
Letters Guessed: [h, l, m, o, n
Category: test
Letters Guessed: [h, l, m, o, n]
Your guess:
有人可以提供一些提示
答案 0 :(得分:0)
您的比较方法无效:
public static boolean compare(char guess, String word){
for(int i = 0; i<word.length(); i++){
if(guess != word.charAt(i)){
return false;
}
}
return true;
}
答案 1 :(得分:0)
首先,您应该像其他人建议的那样修改您的compare()
方法,这样它就不会总是返回true。
其次,您应该使用main()
方法中的返回值。如果比较为真与假,则不清楚你想做什么,所以一般来说,
if (compare(guess, word)) {
/* Do something */
} else {
/* Do something else here */
}
答案 2 :(得分:0)
这篇文章中关于预期产出和实际产出存在一些含糊之处;以下几点必须考虑。
字符串是不可变的,但您使用word.toUpperCase()而不指定它。像:
word = word.toUpperCase();
您正在使用比较方法但未使用其决定,如
if(compare(guess,word)){
//do something
}