【问题标题】:Cannot translate pseudo-code to java [closed]无法将伪代码转换为 java [关闭]
【发布时间】:2018-03-23 11:02:23
【问题描述】:

我从朋友那里得到了一些伪代码形式的测试代码。他请我帮忙发帖。

这是伪代码:

function g(string str) returns string
  int i =0
  string new_str = ""
  while i < len(str) - 1
    new_str = new_str + str [i + 1]
    i++
   end
   return new_str
end

function f(string str) return string
  if len(str) == 0
    return ""
  else if len(str) == 1
    return str
  else 
    return f(g(str) + str [0]
  end
  end

function h(int n, string str) returns string
whlie n != 1
  if n % 2 == 0
    n = n/2
  else
    n = 3 * n + 1
  end
  str = f(str)
  end
    return str
end

function pow(int x, int y) returns int
  if y == 0
    return 1
  else 
    return x * pow(x, y-1)
  end
end

print (h(1, "fruits"))
print (h(2, "fruits"))
print (h(5, "fruits"))
print (h(pow(2, 1000000000000000), "fruits"))
print (h(pow(9831050005000007), "fruits"))

我尝试将其转换为 Java 语法,但在第 20 行和第 32 行出现错误:

不兼容的类型:字符串无法转换为字符串[]

这是我制作的代码:

public class TestLogic{
    public  String g(String[] str){
        int i=0;
        String new_str = "";
        while(i < (str.length -1)){
            new_str += str[1 + i];
            i = i + 1;   
        }
        return new_str;
    }

    public String f(String[] str){
        if (str.length == 0) {
            return "";
        }
        else if (str.length == 1){
            return str.toString();
        }
        else {
            return f(g(str)) + str [0];
        }
    }

    public static String h (int n, String str){
        while(n!=1){
            if (n%2==0){
                n= n/2;
            }
            else{
                n =3*n +1 ;
            }
            str = f(str);
        }
        return str;
    }

    public static int pow(int x, long y){
        if (y==0) {
            return 1;
        }
        else{
            return x * pow(x, y-1);
        }
    }

    public static void main(String[] args) {
        System.out.print(h(1, "fruits"));
        System.out.print(h(2, "fruits"));
        System.out.print(h(5, "fruits"));
        System.out.print(h(pow(2, 1000000000000000l),"fruits"));
       System.out.print(h(pow(2, 9831050005000007l),"fruits"));

    }
}

在这里要明确一点,我不是程序员。而且我是 Java 和编程世界的新手。

【问题讨论】:

  • 是的......................
  • g(str) 正在返回一个不能传递给函数f的字符串
  • 要么OP需要将所述String包装成一个String数组,要么改变函数定义。

标签: java arrays string logic


【解决方案1】:

您的朋友在他的示例中没有使用字符串数组(这是另一种编程语言),他使用的是普通字符串。

当他访问带有括号string [i + 1] 的字符串时,java 中的翻译代码将是string.charAt(i+1)。因此,只需将您的字符串数组更改为普通字符串即可。

【讨论】:

  • 这很有帮助。谢谢你。我将所有 String[] 更改为字符串。还有长度到长度()方法。但是我在第三和第四个输出上遇到了麻烦。我的朋友说我应该在输出中使用 biginteger。我已经尝试过了,但得到一个错误,说 Biginteger 无法转换为 int。你怎么看?
【解决方案2】:

在 f 和 g 中,您传递 sa 参数 aj 字符串数组 (String[]) 字符串无法转换为字符串的 aj 数组,因此如果删除这两个函数的参数类型中的 [] 括号,它应该可以工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 2012-11-21
    • 2012-04-10
    • 1970-01-01
    相关资源
    最近更新 更多