简体   繁体   English

尝试将C清晰代码转换为Java时出现问题

[英]problems trying to convert c sharp code into java

i'm try find most similar string in a array, and i found a code in c sharp that is this one 我尝试在数组中找到最相似的字符串,然后在c Sharp中找到了一个代码

  public static int LevenshteinDistance(string s, string t)
    {
        int n = s.Length;
        int m = t.Length;
        int[,] d = new int[n + 1, m + 1];
        if (n == 0)
        {
            return m;
        }
        if (m == 0)
        {
            return n;
        }

        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= m; j++)
            {
                int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
                Console.WriteLine(cost);
                d[i, j] = Math.Min(
                    Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
                    d[i - 1, j - 1] + cost);


            }
        }
        return d[n, m];
    }

and i'm trying to convert it into java but i get 1 error this is my code in java 我正在尝试将其转换为java,但出现1错误,这是我在java中的代码

    public static int LevenshteinDistance(String s, String t)
       {
         int n = s.length();
        int m = t.length();
        int[][] d = new int[n + 1][ m + 1];
        if (n == 0)
        {
            return m;
        }
        if (m == 0)
        {
            return n;
        }



        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= m; j++)
            {


            int cost = (t[j - 1] == s[i - 1])? 0 : 1;

                d[i][ j] = Math.min(
                    Math.min(d[i - 1][ j] + 1, d[i][ j - 1] + 1),
                    d[i - 1][ j - 1]+cost );
            }
        }
        return d[n] [m];
    }

i get the error in this line of code int cost = (t[j - 1] == s[i - 1]) ? 我在这行代码中得到错误int cost =(t [j-1] == s [i-1])? 0 : 1; 0:1; the error that i have is "Array is required,but string found" this is what i have in my main 我的错误是“数组是必需的,但是找到了字符串”这就是我的主要内容

         String []ray ={"food","drinks","stuffs"};
         String fa="drink";
        for (int i = 0; i < ray.length; i++)
        {

         System.out.print(LevenshteinDistance(fa, ray[i]));
        }

i would appreciate any help 我将不胜感激任何帮助

使用t.charAt(j-1)== s.charAt(i-1)来访问字符串中的字符(字母)您不能直接通过索引(括号[])访问它们。

int cost = (t.charAt(j - 1) == s.charAt(i - 1))? 0 : 1;

You are accessing the strings as arrays here with the [] array operator: 您可以使用[]数组运算符在此处以数组形式访问字符串:

t[j - 1] == s[i - 1]

to get the nth char of a string, instead use .charAt(n) so in this case change it to: 要获取字符串的第n个字符,请改用.charAt(n),在这种情况下,请将其更改为:

t.charAt(j - 1) == s.charAt(i - 1)

the same applies to the rest of the code. 其余代码也是如此。

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

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