2013-11-09 43 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