【发布时间】:2015-03-30 12:00:53
【问题描述】:
所以我想将用户输入带入一个变量,然后将其添加到数组中,但字符直接进入数组并跳过 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:
谁能给点建议
【问题讨论】:
-
注意:
word.toUpperCase();- 字符串是不可变的对象,您应该将结果分配回字符串。你的compare方法也没有意义,它总是返回true。 -
请添加更多关于这应该做什么的更多信息,确切地说。您的代码中有几个问题,但很难判断哪个是真正的错误,哪个是您稍后要实施的错误。这应该是类似于刽子手的东西吗?什么是类别?