2013-11-09 100 views
-1

我的期望輸出是1,4,9和16,但我卡住了。有人知道我的編碼有什麼問題嗎?重複執行對帳單

import java.util.Scanner; 

public class JavaApplication1 { 

    public static void main(String[] args) { 

    Scanner input = new Scanner (System.in); 

    int i = 4; 
    int j = 3; 
    int x = ; 

    while(i >= 1){ 
    } 


     x = (i-j)*(i-j); 
     i = i-1; 
     j = j-2; 

    System.out.println(x); 
    } 
} 
+0

拿一張紙和一支鉛筆,在每次迭代i,j和X寫你得到的值。你會看到會發生什麼,並能夠糾正它並獲得所需的輸出。 –

+0

或..使用DEBUGGER!它在那裏幫助你。 – Maroun

+1

我知道你的編碼有什麼問題 - 你做得太快了,結果陷入了不必要的複雜性,而這種複雜性可以通過預先考慮來避免。少輸入,多想一想! – kviiri

回答

1

基本上,你想要的是一個函數,它的x值平方。有各種各樣的可能性,但你的看起來有點奇怪。如果你對Math類不熟悉,你應該:只有一個變量x,從1開始。詢問x是否小於5(你只想迭代4次)。使計算機執行x * x。

像這樣:

int x = 1; 

while(x < 5){ 
    System.out.println(x*x); 
    x++; //the computer will interpret this as x = x+1 
} 
+0

這將打印1,2,3,4(每個單獨一行)。它應該是'System.out.println(x * x);' –

+0

@PhilipWhitehouse謝謝:) – user2651804