【问题标题】:Novice at Java trying to get first code sample runningJava 新手试图让第一个代码示例运行
【发布时间】:2018-07-27 15:36:50
【问题描述】:

我正在尝试让这段代码 sn-p 运行:

public static void findNeedles(String haystack, String[] needles){
    if(needles.length > 5){
        System.err.println("Too many words!");
    } else {
        int[] countArray = new int[needles.length];
        for(int i = 0; i < needles.length;++){
            String[] words = haystack.split("[\"\'\t\n\b\f\r]", 0);
            for(int j = 0; j < words.length; j++){
                if(words[j].compareTo(needles[i]) == 0){
                    countArray[i]++;
                }
            }
        }
        for(int j = 0; j < needles.length; j++){
            System.out.println(needles[j] + ": " + countArray[j]);
        }
    }
}

知道我应该把这个包裹在"public static void main(String[] args) {"

但语法不正确。

有人帮助新手入门吗?

【问题讨论】:

  • 只需创建您知道的main 方法,然后使用合适的参数从那里调用您自己的方法。
  • 嗨 MJB,欢迎来到 SO。你需要在你的问题上花费更多的精力。
  • 添加public static void main(String[] args){ String haystack = ...; String[] needles = ...; findNeedles(haystack, needles); } 来创建一个主方法。你也可以调用特定的函数而不需要 main
  • @MJB - 不要因反对票而气馁,请阅读 stackoverflow 的帮助部分,以便学习如何编写好的问题和答案。干杯。
  • 我编辑了我的答案以突出显示语法错误。

标签: java syntax


【解决方案1】:

我建议您使用像 Spring Tool Suite、Eclipse IDE 或 InteliJ 这样的 IDE。 它们会突出显示语法错误并提示您可能出现的问题。

您忘记在第一个 for 循环中引用变量 i 时告诉每个循环后如何处理变量。你有; ++,它应该是; i++

所以要从 main 调用你的方法,你可以这样做:

public class YourClass {
    public static void main(String[] args) {
        String[] needles = new String[2];
        findNeedles("some string", needles);
    }

    public static void findNeedles(String haystack, String[] needles){
        if(needles.length > 5){
            System.err.println("Too many words!");
        } else {
            int[] countArray = new int[needles.length];
            for(int i = 0; i < needles.length; i++){
                String[] words = haystack.split("[\"\'\t\n\b\f\r]", 0);
                for(int j = 0; j < words.length; j++){
                   if(words[j].compareTo(needles[i]) == 0){
                        countArray[i]++;
                    }
                }
            }
            for(int j = 0; j < needles.length; j++){
                System.out.println(needles[j] + ": " + countArray[j]);
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    说实话,你的问题不是 java 的语法。我的意思是,这在 java 中是常识。(对不起,如果我因为我的英语不好而显得粗鲁或生硬)

    请找到它。 https://www.journaldev.com/12552/public-static-void-main-string-args-java-main-method 希望对你有帮助。

    【讨论】:

    • @MJB 对不起,我误解了你的问题。我推荐f-CJ的答案。我认为这是最好的,他是一个非常善良的人:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多