任何知道Python和Java的人都可以在這裏幫助我。無法將Python代碼轉換爲Java
我只是想從我知道如何用Python編寫的簡單程序轉換成Java,但我顯然做了一些簡單的錯誤。
這裏是Python代碼:
def correct(a, b, c):
if a + b == 6 and a**2 + b**2 + c**2 == 18:
return True
else:
return False
def show(a, b, c):
print("a is", a, "\nb is", b, "\nc is", c)
def test(a=1, b=1, c=1):
"""Find the value of c, where:
a + b = 6 and a*a + b*b + c*c = 18
"""
for i in range (-10, 10):
a = i
if correct(a, b, c):
show(a, b, c)
return
for j in range(-10, 10):
b = j
if correct(a, b, c):
show(a, b, c)
return
for k in range(-10, 10):
c = k
if correct(a, b, c):
show(a, b, c)
return
print("Nothing worked...")
test()
輸出:
a is 3
b is 3
c is 0
這裏是我的Java版本的嘗試:
private class test {
/* Find the value of c, where:
* a + b = 6 AND a*a + b*b + c*c = 18
*/
public static void main(String[] args) {
int a = 1;
int b = 1;
int c = 1;
for(int i = -10; i == 10; i++) {
a = i;
if (correct(a, b, c)) {
show(a, b, c);
}
for (int j = -10; j == 10; j++) {
b = j;
if (correct(a, b, c)) {
show(a, b, c);
}
for (int k = -10; k == 10; k++) {
c = k;
if (correct(a, b, c)) {
show(a, b, c);
}
}
}
}
System.out.println("Nothing worked...");
}
public static void show(int a, int b, int c) {
System.out.printf("a is: %s\nb is: %s\nc is: %s", a, b, c);
}
private static boolean correct(int a, int b, int c) {
if (a + b == 6 && a*a + b*b + c*c == 18) {
return true;
}
else {
return false;
}
}
}
輸出:
"Nothing worked..."
請問有人請直接告訴我嗎?
很多謝謝。
請將此表述爲[mcve]。解釋代碼應該做什麼。解釋你期望它做什麼。解釋你正在編寫的代碼是如何失敗的。你最終要求社區爲你解決這個問題,這是一個不公平的問題。 – idjaw
你覺得'for(int i = -10; i == 10; i ++)'循環會運行多久? –
您只需在最內層的循環內進行檢查,該檢查已涵蓋所有組合。你可以使用'i','j'和'k',而不需要'a','b'和'c'。 –