【问题标题】:Trying to understand a java function parameters试图理解一个java函数的参数
【发布时间】:2014-06-06 01:53:23
【问题描述】:

我的老师布置了一个问题,这里是:

编写一个将单词输入数组的程序。当一个单词输入两次时,程序将停止。使用以下方法:

static boolean findWord(String s, String[] arr) 
// return true if s is found in arr, false otherwise

输入完成后,你的程序会按排序顺序输出列表。

我对函数的这个参数有点迷茫

String[] arr

它正在搜索什么类型的参数输入。到目前为止,这是我的代码。

public static void main (String[] args) {
        c = new Console ();

        String words[] = new String[50000];

        for(int i=0;i>-1;i++) {
            c.print("Input word: ");
            words[i]=c.readLine();

            findWord("apples",What goes here?);
        }
    }

    static boolean findWord(String s,String[] words) {
        return false;
    }

任何时候我尝试在现场放入某种数组或值,例如

findWord("Hello",words[0]) 

或者我得到以下错误:

No applicable overload method named "findWord" was found in type E3_Q5. Perhaps you     wanted the overloaded version "boolean findWord(java.lang.String s,java.lang.String[] words);" instead?

这是什么意思?他想让我放什么?

【问题讨论】:

  • words[0] 是做什么的?您的方法期望作为第二个参数是什么?
  • 我不知道。问我的老师。同样 words[0] 访问 words 数组的 0 索引。
  • findWord 应该做什么?它需要什么来完成它的工作?
  • 我假设,它需要当前单词和数组位置,如果在数组中找到该单词,则返回 true 或 false
  • 如果您不理解您的作业,需要向您的老师寻求说明。您的方法被声明为static boolean findWord(String s,String[] words) {。第二个参数的类型为String[]。你在findWord("Hello",words[0]) 中作为第二个参数传递了什么? word[0] 是什么? `

标签: java function parameters


【解决方案1】:

String[] arr 指的是String 类型的数组。

使用findWord("Hello",words[0]) 不起作用,因为当方法或函数需要words 或称为words整个数组 时,您只提供一个字符串words[0]

试试这个”

findWord("apples", words);

注意:您需要修改您的方法findWord(String s,String[] words),因为它目前总是返回false

public static boolean findWord(String s, String[] words) {
    for(String word : words) {
            if (s.equals(word))
                return true;
    }

    return false;
}

【讨论】:

  • for 循环不包含三个部分吗?当我尝试(字符串单词:单词)时。我收到了错误的构造错误。
  • @unableToCompile 叫Enhanced for loop,完全没问题。
  • 此代码在每次调用时检查整个重复数组。您应该看到有问题,因为没有使用参数s。您需要遍历数组并搜索s。无论如何,发布所有代码并不能帮助 OP 学习。
  • 我只是复制并粘贴了一个旧方法而没有检查,我很抱歉。我修好了。
  • 所以,我的代码编译但总是返回 true,这是为什么呢? pastebin.com/KKmsqgLc
【解决方案2】:

你的功能

findWord(String s, String[] arr)

需要一个字符串作为第一个参数,一个字符串数组作为第二个参数。

根据你的问题应该是:

findWord(words[i],words);

其中 words[i] 是当前单词,words 是所有单词。如果此函数返回 true,则当前单词在 words 中找到并且您的程序应该终止。

【讨论】:

    【解决方案3】:

    words[0] 不再是 String [](字符串数组)。这只是一个字符串。 Java 允许方法具有相同的名称并接受不同的参数——这称为重载。不过,该方法需要一个字符串数组,因此请去掉 [0],然后您就可以进一步实现该方法了。

    findwords("apple", {"apple", "banana", "cookie"});

    【讨论】:

    • 你能举一个 findWord("apples",X); 的例子吗?我想你的意思是这个 findWord("apples",words);
    • 你说得对。我在底部添加了一个示例。祝你好运!
    猜你喜欢
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    相关资源
    最近更新 更多