gpt4 book ai didi

java - 无法将伪代码翻译为java

转载 作者:行者123 更新时间:2023-12-01 17:51:39 26 4
gpt4 key购买 nike

我从我的 friend 那里得到了一些伪代码形式的测试代码。他请求我帮忙在此处发帖。

这是伪代码:

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 行出现错误,其中显示:

Incompatible types : String Cannot be converted to String []

这是我编写的代码:

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 和编程世界真的很陌生。

最佳答案

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

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

关于java - 无法将伪代码翻译为java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49448229/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com