java - 最大限度地减少读/写操作的循环

标签 java while-loop minimize do-while

今天我想最小化的最后一件事是包含 while 和 do-while 循环的代码。原文如下:

class Vereinfache3_edit { 

        public static void main(String [] args) {

           int c1 = Integer.parseInt(args[0]) ;
           int c2 = Integer.parseInt(args[1]) ;
           int c3 = Integer.parseInt(args[2]) ;

/*  1 */           c1 += 7 ; 
/*  2 */           System.out.println( c1 ) ; 

/*  3 */       while (c1 % 8 != 0)
/*  4 */              if ( c1 % 16 == 0 ) ; 
/*  5 */              else
/*  6 */         do 
/*  7 */                 {
/*  8 */                    c1 += 7 ; 
/*  9 */                    System.out.println( c1 ) ; 
/* 10 */                    if ( c2 < c3 )
/* 11 */                       { c1 = c1+c1 ; 
/* 12 */                         c3 ++ ; 
/* 13 */                         c1 /= 2 ; 
/* 14 */                         c3 -= 1 ; 
/* 15 */                       }
/* 16 */                 }
/* 17 */                 while ( c1 % 8 != 0 ) ;

/* 18 */           c1 += 7 ; 
/* 19 */           System.out.println( c1 ) ; 
        }          

}  // end of class Vereinfache3

这是我的最小化版本:

class Vereinfache3 { 

        public static void main(String [] args) {

               int c1 = Integer.parseInt(args[0]);
               int c2 = Integer.parseInt(args[1]) ;
               int c3 = Integer.parseInt(args[2]) ;

               do{
                   c1 += 7 ; 
                   System.out.println( c1 ) ;               
               }while (c1 % 8 != 0);

/* 18 */       c1 += 7 ; 
/* 19 */       System.out.println( c1 ) ; 
        }          

}  // end of class Vereinfache3

它为我生成相同的输出。您是否发现任何错误或可以改进的地方?

尤其是这段代码似乎很棘手:

/*  3 */       while (c1 % 8 != 0)
/*  4 */              if ( c1 % 16 == 0 ) ; 
/*  5 */              else
/*  6 */          do{}

我该如何处理这段时间? while 循环包含什么?

最佳答案

您的最小化版本产生与原始版本相同的结果,原始解决方案和最小化版本的不同输出仅在 c1 % 8 != 0 and c1 % 16 == 0 的情况下才可能发生。 , 这种情况是不可能的,因为 16 的所有倍数也是 8 的倍数..

删除未使用的声明..是我可以建议的唯一改进。 我确实有一个代码更少的解决方案..并不是说它使事情变得更好...我不喜欢代码中有太多系统输出..:)

    int finalBound = ((c1 + 7) % 8 == 0) ? c1 + 7 : 8 * c1;
    for (; c1 <= finalBound; c1 += 7) {
        System.out.println(c1 + 7);
    }

希望有帮助。

关于java - 最大限度地减少读/写操作的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4062970/

相关文章:

java - 为什么 Activemq-web-console 无法在 Fuse Servicemix 4.3.0-fuse-02-00 上运行?

java - Android 不接收广播 UDP,但接收定向 UDP

bash - 删除空格分隔的文本文件中某些索引处的条目

wpf - 双击功能区时禁用最小化或最大化

c# - 取消 WinForm 最小化?

python - 是否可以使用标准库(没有额外模块)最小化 python 中的控制台?

java - Spring 全局异常处理程序 - 不是 MVC

java - 如何从 URL 检索图像并将其存储为 Java 中的 Blob(谷歌应用引擎)

存储过程中的 Mysql 循环错误代码 #1064 [修订]

java - 尝试使用 FileWriter 写入输出文件