简体   繁体   English

如何确定我的用户输入是否与 Java 数组中的值之一匹配

[英]How do I determine if my user input matches one of the values inside my array in Java

I am a newbie in Java and my assignment asks me to do a word guessing console game that implements conditions, loops and arrays.我是 Java 新手,我的作业要求我做一个单词猜谜游戏,它实现了条件、循环和数组。

If I put an input, it should determine if my input is inside the array.如果我输入一个输入,它应该确定我的输入是否在数组内。

import java.util.Scanner;
    
public class LearnCode {
    public static void main(String[] args) {
        String[] guessTheFood = {"burger", "fries", "steak", "chicken", "pizza"};
        String guess = "";
        Scanner input = new Scanner(System.in);
        System.out.println("Guess the food word.");
        guess = input.nextLine();
        for (int i = 0; i < guessTheFood.length; i++) {
            if (guess.equals(guessTheFood[i])) {
                System.out.println("You guessed it");
            } else {
                System.out.println("Oops, you guessed it wrong");
            }
        }
    }
}

However, my output goes但是,我的输出

Guess the food word.
steak
Oops, you guessed it wrong
Oops, you guessed it wrong
You guessed it
Oops, you guessed it wrong
Oops, you guessed it wrong

How do I fix or solve this?我该如何解决或解决这个问题?

You don't need to print negative response for every index.您不需要为每个索引打印否定响应。 If found return 'SUCCESS RESPONSE' or if end of array return 'Failed Response'如果找到返回'SUCCESS RESPONSE'或者如果数组结束返回'Failed Response'

for (int i = 0;; i++) {
        if(i == guessTheFood.length) {
            System.out.println("Oops, you guessed it wrong");
            break;
        }
        if (guess.equals(guessTheFood[i])) {
            System.out.println("You guessed it");
            break;
        }        
   
    }

Here the for-loop condition check is done inside the loop.这里 for 循环条件检查是在循环内完成的。 This is to remove extra Flags and condition check outside the loop.这是为了删除循环外的额外标志和条件检查。

according to your code you are trying to print the result of condition in every iteration of for loop and it cause to multiple print, you can define a vairable for example: isFound and check the array and if it founds make it to true then print the result according to isFound :根据您的代码,您尝试在for loop每次迭代中打印条件的结果,并导致多次打印,您可以定义一个变量,例如: isFound并检查数组,如果找到,则将其设为true然后打印根据isFound结果:

String[] guessTheFood = { "burger", "fries", "steak", "chicken", "pizza" };
String guess = "";
Scanner input = new Scanner(System.in);
boolean isFound = false;
System.out.print("Guess the food word: ");
guess = input.nextLine();

for (int i = 0; i < guessTheFood.length; i++) {
    if (guess.equals(guessTheFood[i])) {
        isFound = true;
    }
}

if (isFound) {
    System.out.print("Guess the food word: ");
} else {
    System.out.println("Oops, you guessed it wrong");
}

you can add another good option to your code to end the loop after the element has been found by adding the break keyword:您可以在代码中添加另一个不错的选项,通过添加break关键字在找到元素后结束循环:

for (int i = 0; i < guessTheFood.length; i++) {
    if (guess.equals(guessTheFood[i])) {
        isFound = true;
        break;
    }
}

Only print the result when all are checked:仅在检查所有内容时打印结果:

for (int i = 0; i < guessTheFood.length; i++) {
        if (guess.equals(guessTheFood[i])) {
            System.out.println("You guessed it");
        } else {
            System.out.println("Oops, you guessed it wrong");
        }
    }

This will print "guessed" or "wrong" for every check.这将为每张支票打印“猜测”或“错误”。 You don't want that.你不想那样。 Two things you want to change:你想改变的两件事:

  1. Only print after all the (necessary) checks are made仅在完成所有(必要的)检查后才打印
  2. Only check while you have to.只在必要时检查。 If the second element matches, there is no reason to check the rest如果第二个元素匹配,则没有理由检查其余元素

To print after, do something like this:要在之后打印,请执行以下操作:

boolean result = false;
for (int i = 0; i < guessTheFood.length; i++) {
    if (guess.equals(guessTheFood[i])) {
        result = true;
    }
}
// take the printing out of the loop, so it won't iterate with the rest
if ( result ) {
  System.out.println("You guessed it");
} else {
  System.out.println("Oops, you guessed wrong");
}

In order to check only what you need to check, break from the loop once the element is found:为了只检查您需要检查的内容,一旦找到元素,就中断循环:

boolean result = false;
for (int i = 0; i < guessTheFood.length; i++) {
    if (guess.equals(guessTheFood[i])) {
        result = true;
        break; // break out of the loop, you've found your answer
    }
}
if ( result ) {
  System.out.println("You guessed it");
} else {
  System.out.println("Oops, you guessed wrong");
}

You can do it by adding a boolean flag to see if you have found the value or not.您可以通过添加一个布尔flag来查看是否找到了该值。 Then on the basis of the flag you can print the result instead of printing it in each iteration.然后在标志的基础上你可以打印结果而不是在每次迭代中打印它。 Refer code below.参考下面的代码。

 public static void main(String []args){
    String[] guessTheFood = {"burger", "fries", "steak", "chicken", "pizza"};
    String guess = "";
    Scanner input = new Scanner(System.in);
    System.out.println("Guess the food word.");
    guess = input.nextLine();
    boolean flag = false;                             // <==== creating flag here
    for (int i = 0; i < guessTheFood.length; i++) {
        if (guess.equals(guessTheFood[i])) {
            flag = true;                             // <==== changing it to true if value is found
            
        }
}
if(flag)System.out.println("You guessed it");        // <==== using it's value to print result 
else System.out.println("Oops, you guessed it wrong");
 }

Like maloomeister said.就像maloomeister 说的那样。 You can use List:您可以使用列表:

    public class LearnCode {
      public static void main(String[] args) {
        String[] guessTheFood = {"burger", "fries", "steak", "chicken", "pizza"};
        List<String> guessFood = new ArrayList<>(Arrays.asList(guessTheFood));
        Scanner input = new Scanner(System.in);
        System.out.println("Guess the food word.");
        String guess = input.nextLine();
    
        if (guessFood.contains(guess.toLowerCase())) {
          System.out.println("Match");
        } else {
          System.out.println("No Match");
        }
      }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM