2011-05-18 121 views
0

这个计划应该这样做此代码可以更有效吗?

N 10*N 100*N 1000*N 
1 10 100 1000 
2 20 200 2000 
3 30 300 3000 
4 40 400  4000 
5 50 500 5000 

因此,这里是我的代码:

public class ex_4_21 { 

    public static void main(String Args[]){ 

    int process = 1; 
    int process2 = 1; 
    int process22 = 1; 
    int process3 = 1; 
    int process33 = 2; 

    System.out.println("N 10*N 100*N 1000*N"); 
    while(process<=5){ 

     while(process2<=3){ 
     System.out.printf("%d ",process2); 

     while(process22<=3){ 
      process2 = process2 * 10; 
      System.out.printf("%d  ",process2); 
      process22++; 
     } 
     process2++; 
     } 


     process++; 
    } 

    } 
} 

可我的代码更effecient?我目前正在学习while循环。到目前为止,这是我得到的。任何人都可以使这个更有效率,或给我如何使我的代码更有效的想法?

这不是一门功课,我是自我学习的java

+1

此代码不打印。此代码中没有任何内容在行之间输出换行符。只需打印整个文件而不是循环或使用“String.format”插值,可以使效率更高。 – 2011-05-18 17:07:24

+0

这是功课吗? – 2011-05-18 17:08:38

回答

1

您可以使用一个变量n做到这一点。

while(n is less than the maximum value that you wish n to be) 
    print n and a tab 
    print n * 10 and a tab 
    print n * 100 and a tab 
    print n * 1000 and a new line 
    n++ 

如果10的功率是可变的,那么你可以试试这个:

while(n is less than the maximum value that you wish n to be) 
    while(i is less than the max power of ten) 
     print n * i * 10 and a tab 
     i++ 
    print a newline 
    n++ 
0

如果你必须使用一个while循环

public class ex_4_21 { 

public static void main(String Args[]){ 

int process = 1; 

System.out.println("N 10*N 100*N 1000*N"); 
while(process<=5){ 

    System.out.println(process + " " + 10*process + " " + 100*process + " " + 1000*process + "\n"); 
    process++; 
} 

} 
} 
0

你有一个while循环太多(您“process2”while while循环是不必要的)。您也似乎有一些错误,这些错误与您在内部循环中循环的变量在每次迭代中不会重新初始化有关。

我也建议不要使用while循环;你的例子更适合for循环;我知道你正在学习循环机制,但是学习的一部分也应该在决定何时使用哪种构造。这实际上不是性能建议,更多的是方法建议。

我没有任何进一步的性能改进建议,对于您正在尝试做的事情;你可以明显地移除循环(下降到单个或者甚至没有循环),但是两个循环对于你正在做的事情是有意义的(允许你以最小的改变容易地向输出添加另一行或列)。

0

您可以尝试循环展开,类似于@Vincent Ramdhanie的回答。

但是,循环展开和线程化不会为这样一个小样本产生显着的性能改进。创建和启动线程(进程)所涉及的开销比简单的while循环需要更多的时间。 I/O中的开销比展开的版本节省更多的时间。一个复杂的程序比简单的程序更难调试和维护。

你在想这叫做微优化。只有在无法满足需求或客户需求时,才能保存较大程序的优化。