且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将输入值与数组的每个值进行比较?

更新时间:2021-12-06 00:27:03

将查找值的过程与请求的过程分开。这是两个不同的操作:

Separate the process of finding the value from the process of asking for a value. This is two distinct operations:


  • 询问字符串

  • 给出一个字符串,进行搜索在数组中(一个适当的数组,声明为 String []

  • Ask for a string
  • Given a string, search for it in your array (a proper array, declared as String[])

这是一个提示。我建议将这些东西弄清楚。

Here's a hint. I'd recommend breaking those things out.

public boolean findWord(String candidateWord) {
    for(String word : string) {
        if(word.equals(candidateWord)) {
            return true;
        }
    }
    return false;
}

public void askForWords() {
    System.out.println("Find a word! ");
    Scanner scan = new Scanner(System.in);
    String candidateWord;
    boolean found = false;
    do {
         System.out.print("What word do you want to find? ");
         found = findWord(scan.nextLine());
         if(!found) {
             System.out.println("Can't find that - try again?");
             System.out.print("What word do you want to find? ");
             scan.nextLine();
          }
     } while(!found);
}