Java,如何比较字符串和字符串数组

18

我在这里搜索了一段时间,但还没有找到答案。

我的大学作业要求我使用一个数组。然后,我应该检查输入的字符串是否与存储在字符串数组中的任何内容匹配。

我知道可以使用.equals() 方法轻松比较字符串。然而,同样的方法不能用于字符串数组。

为了在StackOverflow上解释,请参考下面的示例代码。

我做错了什么?

import java.util.Scanner;

class IdiocyCentral {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        /*Prints out the welcome message at the top of the screen*/
        System.out.printf("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
        System.out.printf("%55s", "=================================\n");

        String [] codes = {"G22", "K13", "I30", "S20"};

        System.out.printf("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2], codes[3]);
        System.out.printf("Enter one of the above!\n");

        String usercode = in.nextLine();

        if (codes.equals(usercode)) {
            System.out.printf("What's the matter with you?\n");
        }
        else {
            System.out.printf("Youda man!");
        }

    }
}

如果这个问题之前已经被问过而我错过了,那么我很抱歉。如果这是一个重复的问题,我会将其删除。


1
你需要循环遍历数组并单独检查每个字符串。 - Dave Newton
6个回答

58

我猜你想要检查数组是否包含某个值,是吗?如果是的话,请使用contains方法。

if(Arrays.asList(codes).contains(userCode))

@PeterOlsen 啊,终于我能接受你的答案了。非常感谢! - Nico
3
@PeterOlsen - 这可能是最简洁的解决方案,但我预计问题提问者的教练希望他/她使用循环编写代码……并在此过程中,练习使用数组和循环。 - Stephen C
@StephenC 这只是代码的一部分,按照PeterOlsen的建议已经完美了。我需要使用循环,但这与代码的这部分是分开的 :) - Nico

3

现在你似乎在问“这个字符串数组是否等于这个字符串”,当然它永远不会相等。

也许你应该考虑使用循环遍历字符串数组,并检查每个字符串是否与输入的字符串相等?

或者我误解了你的问题?


@PeterOlsen建议的方法有效。我正在等待能够接受他的答案。如果我的问题不够清晰,对不起。 - Nico
没问题。既然这是一道大学问题,我想你的教练可能希望你学习控制流程,比如循环等等。话虽如此,也许你在大学课程中已经超越了这个阶段 :) - f1dave

3

使用循环迭代codes数组,对每个元素询问它是否等于usercode。如果有一个元素相等,您可以停止并处理该情况。如果没有任何一个元素等于usercode,则执行适当的操作来处理该情况。伪代码如下:

found = false
foreach element in array:
  if element.equals(usercode):
    found = true
    break

if found:
  print "I found it!"
else:
  print "I didn't find it"

当我浏览伪代码时,我几乎立刻认为它是Python。 - Peter Olson

1
如果我正确理解了你的问题,那么你想知道以下内容:
如何检查我的字符串数组是否包含刚输入的usercode字符串?
请参考这里中类似的问题。它引用了之前答案中指出的解决方案。希望这可以帮到你。

1

你可以直接使用 ArrayList,而不是使用数组,并且可以使用 contains 方法来检查你传递给 ArrayList 的值。


1
import java.util.Scanner;
import java.util.*;
public class Main
{
  public static void main (String[]args) throws Exception
  {
    Scanner in = new Scanner (System.in);
    /*Prints out the welcome message at the top of the screen */
      System.out.printf ("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
      System.out.printf ("%55s", "=================================\n");

      String[] codes =
    {
    "G22", "K13", "I30", "S20"};

      System.out.printf ("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2],
             codes[3]);
      System.out.printf ("Enter one of the above!\n");

    String usercode = in.nextLine ();
    for (int i = 0; i < codes.length; i++)
      {
    if (codes[i].equals (usercode))
      {
        System.out.printf ("What's the matter with you?\n");
      }
    else
      {
        System.out.printf ("Youda man!");
      }
      }

  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接