简体   繁体   English

我的Java代码错误

[英]Error in my Java code

I've got a problem with my Java program. 我的Java程序有问题。 There is an error in my code on line 16 ( t = T[i]; ) which implies an error on line 12. It says : 我的代码在第16行有一个错误( t = T[i]; ),这意味着在第12行有错误。它说:

Syntax error on token "=",VariableInitializer expected after this token.

Could I have some help ? 我可以帮忙吗?

public class Ngrams {

    public static boolean estPrefixe(String t, String s) {
        int Longs = s.length();
        if (t.substring(0, Longs) == s) {
            return true;
        } else {
            return false;
        }
    }

    public static int nbOccurences(String[] T, String s) {
        int compteur = 0;
        String t = null;
        for (int i = 0; i < T.length; i++) {
            t = T[i];
            if (estPrefixe(t, s)) {
                compteur++;
            }
            return compteur;
        }
    }

Notwithstanding the fact that you're comparing Strings with == instead of .equals() , and that a right bracket seems to have gone AWOL, at the end of your program, you're "missing" a return statement in nbOccurences . 尽管您正在使用==而不是.equals()来比较字符串,并且右括号似乎已经消失了,但在程序结尾,您在nbOccurences “缺少”了一个return语句。 Even though you have one in the for-loop, if you never enter the loop, you don't return anything. 即使您在for循环中有一个循环,如果您从不进入循环,则不会返回任何内容。

Move your return statement down one line, outside of the loop instead. 将return语句向下移动一行,而不是在循环之外。

public static int nbOccurences(String[] T, String s) {
    int compteur = 0;
    String t = null;
    for (int i = 0; i < T.length; i++) {
        t = T[i];
        if (estPrefixe(t, s)) {
            compteur++;
        }
    }
    return compteur;
}

The method nbOccurences does not always return an int value. 方法nbOccurences并不总是返回int值。 If T is null or empty (length = 0) no value is returned. 如果T为null或为空(长度= 0),则不返回任何值。 So you should add another return statement after the for loop. 因此,您应该在for循环之后添加另一个return语句。

As others mentioned already you should use equals to compare strings. 正如其他人已经提到的那样,您应该使用equals来比较字符串。 This however, is not producing a syntax error. 但是,这不会产生语法错误。

Well there's a serious bug in this line: 好吧,这行有一个严重的错误:

if (t.substring(0, Longs) == s) {

This test will always be false, because == compares object references, not values. 该测试将始终为false,因为==比较对象引用而不是值。 Change it to: 更改为:

if (t.substring(0, Longs).equals(s)) {

But the whole method is pointless. 但是整个方法是没有意义的。 Change it to: 更改为:

public static boolean estPrefixe(String t, String s) {
    return t.startsWith(s);
}

Or just delete the method altogether because it adds no value whatsoever. 或完全删除该方法,因为它不会增加任何价值。

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

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