坚持为我的游戏发表if陈述

时间:2019-01-16 13:41:35

标签: java

尝试为游戏创建if语句,在该语句中,我给用户一个加扰的单词,而他们必须输入由那些加扰的字母组成的单词。我已经硬编码了三个可以使用的答案。我坚持尝试做出IF else语句,以告知用户答案是否正确或重试。

import java.util.*; 
public class Scramble {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String[] wordbank = new String [10];
        int answer; 
        wordbank[0] = "GALEE";
        wordbank[1] = "OLWBE"; 
        wordbank[2] = "RHCIA"; 
        wordbank[3] = "RWSIT"; 
        wordbank[4] = "NTARI"; 
        wordbank[5] = "ETLBA"; 
        wordbank[6] = "TIRSH"; 
        wordbank[7] = "TLUFE"; 
        wordbank[8] = "MIGEIN"; 
        wordbank[9] = "RAEHT"; 
        String[] GALEE = {"Eagle", "Gale", "Leg"};
        String[] OLWBE = {"Elbow", "Below", "Lobe"}; 
        String[] RHCIA = {"Chair", "Hair", "Air"}; 
        String[] RWSIT = {"Wrist", "Wit", "It"}; 
        String[] NTARI = {"Train", "Rant", "Art"}; 
        String[] ETBLA = {"Table", "Late", "Bet"}; 
        String[] TIRSH = {"Shirt", "Sir", "Sh"}; 
        String[] TLUFE = {"Flute", "Felt", "let"}; 
        String[] MIGEIN = {"Gemini", "Mini", "Gem"}; 
        String[] RAEHT = {"Heart", "Hate", "Ear"}; 

        System.out.println("Create a five letter word out of " + wordbank[0] + ".");
        answer = s.nextInt();
        if (answer) { 

        }

3 个答案:

答案 0 :(得分:1)

如Arnaud的评论中所述,您可能应该使用next(),至少应检查answer的值确实是用户输入的内容。

一旦这一切都解决了,您将需要检查answer是三个可接受的解决方案之一。

您可以在Java 8中使用它:

boolean resultOk = Arrays.asList(GALEE).contains(answer);
if (resultOK) {
    // do something
}

这将检查answer是否属于您的GALEE数组(因此它必须等于eaglegaleleg

答案 1 :(得分:0)

假设用户键入了该单词,则需要使用next()而不是nextInt()来阅读它。

if语句读取一个布尔值,在这种情况下,该布尔值应来自比较(例如,equals是一种简单的解决方案)。

if(answer.equals("Eagle")){
  //do something
}

有关更多信息,请参见How do I compare strings in Java?

或者,为获得更好的解决方案,如果用户给出的答案与数组的某些元素匹配,则应尝试仅一步检查

if(Arrays.asList(GALEE).contains(answer)){
  //do something
}

为此,您可以检查How do I determine whether an array contains a particular value in Java?

答案 2 :(得分:0)

您可以简单地遍历GALEE以查看他们输入的内容是否等于GALEE中的单词之一。 这是您的代码应如下所示:

String answer = scanner.nextLine();
boolean matches = false;

for(String combination: GALEE){
    if(answer.equals(combination)){
        matches = true;
        break
    }
}
if(matches){
    System.out.println("You got it correct!");
} else{
    System.out.println("You got it wrong!");
}

我还要指出,您要求他们

  

创建一个五个字母的单词

但是GALEE中的某些单词少于5个字母长。